From 10b2eb40718ed89aec74ee2e26c18caade5ea848 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 23 Oct 2025 12:42:10 -0400 Subject: [PATCH 01/46] draft poolv3 with agnostic price --- .../LenderCommitmentGroup_Pool_V3.sol | 1583 +++++++++++++++++ .../price_adapters/PriceAdapterUniswapV3.sol | 4 +- 2 files changed, 1585 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol new file mode 100644 index 000000000..6a15189e0 --- /dev/null +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -0,0 +1,1583 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + + +// Contracts +import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; + + +// Interfaces +import "../../../interfaces/ITellerV2Context.sol"; +import "../../../interfaces/IProtocolFee.sol"; + +import "../../../interfaces/ITellerV2.sol"; + +import "../../../libraries/NumbersLib.sol"; + +import "../../../interfaces/uniswap/IUniswapV3Pool.sol"; + + +import "../../../interfaces/IHasProtocolPausingManager.sol"; + +import "../../../interfaces/IProtocolPausingManager.sol"; + + + +import "../../../interfaces/ISmartCommitmentForwarder.sol"; + +import "../../../libraries/uniswap/TickMath.sol"; +import "../../../libraries/uniswap/FixedPoint96.sol"; +import "../../../libraries/uniswap/FullMath.sol"; + + +import { LenderCommitmentGroupSharesIntegrated } from "./LenderCommitmentGroupSharesIntegrated.sol"; + +import {OracleProtectedChild} from "../../../oracleprotection/OracleProtectedChild.sol"; + +import { MathUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; + + + +import { IERC4626 } from "../../../interfaces/IERC4626.sol"; + +import { CommitmentCollateralType, ISmartCommitment } from "../../../interfaces/ISmartCommitment.sol"; +import { ILoanRepaymentListener } from "../../../interfaces/ILoanRepaymentListener.sol"; + +import { ILoanRepaymentCallbacks } from "../../../interfaces/ILoanRepaymentCallbacks.sol"; + +import { IEscrowVault } from "../../../interfaces/IEscrowVault.sol"; + +import { IPausableTimestamp } from "../../../interfaces/IPausableTimestamp.sol"; +import { ILenderCommitmentGroup_V2 } from "../../../interfaces/ILenderCommitmentGroup_V2.sol"; +import { Payment } from "../../../TellerV2Storage.sol"; + +import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; +import {UniswapPricingLibraryV2} from "../../../libraries/UniswapPricingLibraryV2.sol"; + + +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; +import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; + + + +/* + + + Each LenderCommitmentGroup SmartContract acts as its own Loan Commitment (for the SmartCommitmentForwarder) and acts as its own Lender in the Teller Protocol. + + 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. + + 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. + 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. + + 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. + + +*/ + +contract LenderCommitmentGroup_Pool_V2 is + ILenderCommitmentGroup_V2, + IERC4626, // interface functions for lenders + ISmartCommitment, // interface functions for borrowers (teller protocol) + ILoanRepaymentListener, + IPausableTimestamp, + Initializable, + OracleProtectedChild, + OwnableUpgradeable, + ReentrancyGuardUpgradeable, + LenderCommitmentGroupSharesIntegrated +{ + using AddressUpgradeable for address; + using NumbersLib for uint256; + + uint256 public immutable STANDARD_EXPANSION_FACTOR = 1e18; + + uint256 public immutable MIN_TWAP_INTERVAL = 3; + + uint256 public immutable UNISWAP_EXPANSION_FACTOR = 2**96; + + uint256 public immutable EXCHANGE_RATE_EXPANSION_FACTOR = 1e36; + + using SafeERC20 for IERC20; + + /// @custom:oz-upgrades-unsafe-allow state-variable-immutable + address public immutable TELLER_V2; + address public immutable SMART_COMMITMENT_FORWARDER; + address public immutable PRICE_ADAPTER; + + + + IERC20 public principalToken; + IERC20 public collateralToken; + + uint256 marketId; + + + uint256 public totalPrincipalTokensCommitted; + uint256 public totalPrincipalTokensWithdrawn; + + uint256 public totalPrincipalTokensLended; + uint256 public totalPrincipalTokensRepaid; //subtract this and the above to find total principal tokens outstanding for loans + uint256 public excessivePrincipalTokensRepaid; + + uint256 public totalInterestCollected; + + uint16 public liquidityThresholdPercent; //max ratio of principal allowed to be borrowed vs escrowed // maximum of 10000 (100%) + uint16 public collateralRatio; //the overcollateralization ratio, typically >100 pct + + uint32 public maxLoanDuration; + uint16 public interestRateLowerBound; + uint16 public interestRateUpperBound; + + + + + uint256 immutable public DEFAULT_WITHDRAW_DELAY_TIME_SECONDS = 300; + uint256 immutable public MAX_WITHDRAW_DELAY_TIME = 86400; + + mapping(uint256 => bool) public activeBids; + mapping(uint256 => uint256) public activeBidsAmountDueRemaining; + + int256 tokenDifferenceFromLiquidations; + + bool public firstDepositMade; + uint256 public withdrawDelayTimeSeconds; + + IUniswapPricingLibrary.PoolRouteConfig[] public poolOracleRoutes; + + //configured by the owner. If 0 , not used. + uint256 public maxPrincipalPerCollateralAmount; + + + uint256 public lastUnpausedAt; + bool public paused; + bool public borrowingPaused; + bool public liquidationAuctionPaused; + + + bytes32 public priceRouteHash; + + + event PoolInitialized( + address indexed principalTokenAddress, + address indexed collateralTokenAddress, + uint256 marketId, + uint32 maxLoanDuration, + uint16 interestRateLowerBound, + uint16 interestRateUpperBound, + uint16 liquidityThresholdPercent, + uint16 loanToValuePercent + ); + + + + event BorrowerAcceptedFunds( + address indexed borrower, + uint256 indexed bidId, + uint256 principalAmount, + uint256 collateralAmount, + uint32 loanDuration, + uint16 interestRate + ); + + + + event DefaultedLoanLiquidated( + uint256 indexed bidId, + address indexed liquidator, + uint256 amountDue, + int256 tokenAmountDifference + ); + + + event LoanRepaid( + uint256 indexed bidId, + address indexed repayer, + uint256 principalAmount, + uint256 interestAmount, + uint256 totalPrincipalRepaid, + uint256 totalInterestCollected + ); + + + event WithdrawFromEscrow( + + uint256 indexed amount + + ); + + + modifier onlySmartCommitmentForwarder() { + require( + msg.sender == address(SMART_COMMITMENT_FORWARDER), + "OSCF" + ); + _; + } + + modifier onlyTellerV2() { + require( + msg.sender == address(TELLER_V2), + "OTV2" + ); + _; + } + + + modifier onlyProtocolOwner() { + require( + msg.sender == Ownable(address(TELLER_V2)).owner(), + "OO" + ); + _; + } + + modifier onlyProtocolPauser() { + + address pausingManager = IHasProtocolPausingManager( address(TELLER_V2) ).getProtocolPausingManager(); + + require( + IProtocolPausingManager( pausingManager ).isPauser(msg.sender) , + "OP" + ); + _; + } + + modifier bidIsActiveForGroup(uint256 _bidId) { + require(activeBids[_bidId] == true, "BNA"); + + _; + } + + + modifier whenForwarderNotPaused() { + require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , "SCF_P"); + _; + } + + + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor( + address _tellerV2, + address _smartCommitmentForwarder, + + address _priceAdapter + ) OracleProtectedChild(_smartCommitmentForwarder) { + TELLER_V2 = _tellerV2; + SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder; + + PRICE_ADAPTER = _priceAdapter; + } + + /** + * @notice Initializes the LenderCommitmentGroup_Smart contract. + * @param _commitmentGroupConfig Configuration for the commitment group (lending pool). + * @param _poolOracleRoutes Route configuration for the principal/collateral oracle. + + */ + function initialize( + + CommitmentGroupConfig calldata _commitmentGroupConfig, + + bytes calldata _priceAdapterRoute, + + //IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes + + ) external initializer { + + __Ownable_init(); + + __Shares_init( + _commitmentGroupConfig.principalTokenAddress, + _commitmentGroupConfig.collateralTokenAddress + ); //initialize the integrated shares + + principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress); + collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress); + + marketId = _commitmentGroupConfig.marketId; + + withdrawDelayTimeSeconds = DEFAULT_WITHDRAW_DELAY_TIME_SECONDS; + + //in order for this to succeed, first, the SmartCommitmentForwarder needs to be a trusted forwarder for the market + ITellerV2Context(TELLER_V2).approveMarketForwarder( + _commitmentGroupConfig.marketId, + SMART_COMMITMENT_FORWARDER + ); + + maxLoanDuration = _commitmentGroupConfig.maxLoanDuration; + interestRateLowerBound = _commitmentGroupConfig.interestRateLowerBound; + interestRateUpperBound = _commitmentGroupConfig.interestRateUpperBound; + + require(interestRateLowerBound <= interestRateUpperBound, "IRLB"); + + + liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent; + collateralRatio = _commitmentGroupConfig.collateralRatio; + + require( liquidityThresholdPercent <= 10000, "ILTP"); + + for (uint256 i = 0; i < _poolOracleRoutes.length; i++) { + poolOracleRoutes.push(_poolOracleRoutes[i]); + } + + + // require(poolOracleRoutes.length >= 1 && poolOracleRoutes.length <= 2, "PRL"); + + + // we register the price route with the adapter and save it locally + priceRouteHash = IPriceAdapter( _priceAdapter ).registerPriceRoute( + _priceAdapterRoute + ); + + + + emit PoolInitialized( + _commitmentGroupConfig.principalTokenAddress, + _commitmentGroupConfig.collateralTokenAddress, + _commitmentGroupConfig.marketId, + _commitmentGroupConfig.maxLoanDuration, + _commitmentGroupConfig.interestRateLowerBound, + _commitmentGroupConfig.interestRateUpperBound, + _commitmentGroupConfig.liquidityThresholdPercent, + _commitmentGroupConfig.collateralRatio + ); + } + + + + /** + * @notice Validates loan parameters and starts the TellerV2 Loan where this contract as the lender. + * @dev Must be called via the Smart Commitment Forwarder + * @param _borrower Address of the borrower accepting the loan. + * @param _bidId Identifier for the loan bid. + * @param _principalAmount Amount of principal being lent. + * @param _collateralAmount Amount of collateral provided by the borrower. + * @param _collateralTokenAddress Address of the collateral token contract. + * @param _collateralTokenId Token ID of the collateral (if applicable). + * @param _loanDuration Duration of the loan in seconds. + * @param _interestRate Interest rate for the loan, scaled by 100 (e.g., 500 = 5%). + */ + function acceptFundsForAcceptBid( + address _borrower, + uint256 _bidId, + uint256 _principalAmount, + uint256 _collateralAmount, + address _collateralTokenAddress, + uint256 _collateralTokenId, + uint32 _loanDuration, + uint16 _interestRate + ) external onlySmartCommitmentForwarder whenForwarderNotPaused whenNotPaused whenBorrowingNotPaused { + + require( + _collateralTokenAddress == address(collateralToken), + "MMCT" + ); + //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 >= getMinInterestRate(_principalAmount), "IIR"); + //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 <= maxLoanDuration, "LMD"); + + require( + getPrincipalAmountAvailableToBorrow() >= _principalAmount, + "LMP" + ); + + + uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal( + _principalAmount + ); + + + + require( + _collateralAmount >= + requiredCollateral, + "C" + ); + + principalToken.safeApprove(address(TELLER_V2), _principalAmount); + + //do not have to override msg.sender here as this contract is the lender ! + _acceptBidWithRepaymentListener(_bidId); + + totalPrincipalTokensLended += _principalAmount; + + activeBids[_bidId] = true; //bool for now + activeBidsAmountDueRemaining[_bidId] = _principalAmount; + + + emit BorrowerAcceptedFunds( + _borrower, + _bidId, + _principalAmount, + _collateralAmount, + _loanDuration, + _interestRate + ); + } + + /** + * @notice Internal function to accept a loan bid and set a repayment listener. + * @dev Interacts with the Teller Protocol to accept the bid and register the repayment listener. + * @param _bidId Identifier for the loan bid being accepted. + */ + function _acceptBidWithRepaymentListener(uint256 _bidId) internal { + + ITellerV2(TELLER_V2).lenderAcceptBid(_bidId); //this gives out the funds to the borrower + + ILoanRepaymentCallbacks(TELLER_V2).setRepaymentListenerForBid( + _bidId, + address(this) + ); + + + } + + /** + * @notice Liquidates a defaulted loan using a reverse auction that starts high and falls to zero. + * @dev The amount of tokens withdrawn from the liquidator is always the sum of _tokenAmountDifference + amountDue . + * @dev Handles the liquidation process for a defaulted loan bid, ensuring all conditions for liquidation are met. + * @param _bidId Identifier for the defaulted loan bid. + * @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. + */ + function liquidateDefaultedLoanWithIncentive( + uint256 _bidId, + int256 _tokenAmountDifference + ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused whenNotPaused bidIsActiveForGroup(_bidId) nonReentrant onlyOracleApprovedAllowEOA { + + + + uint256 loanTotalPrincipalAmount = _getLoanTotalPrincipalAmount(_bidId); //only used for the auction delta amount + + (uint256 principalDue,uint256 interestDue) = _getAmountOwedForBid(_bidId); //this is the base amount that must be repaid by the liquidator + + + uint256 loanDefaultedTimeStamp = ITellerV2(TELLER_V2) + .getLoanDefaultTimestamp(_bidId); + + uint256 loanDefaultedOrUnpausedAtTimeStamp = Math.max( + loanDefaultedTimeStamp, + getLastUnpausedAt() + ); + + int256 minAmountDifference = getMinimumAmountDifferenceToCloseDefaultedLoan( + loanTotalPrincipalAmount, + loanDefaultedOrUnpausedAtTimeStamp + ); + + + require( + _tokenAmountDifference >= minAmountDifference, + "TAD" + ); + + + if (minAmountDifference > 0) { + //this is used when the collateral value is higher than the principal (rare) + //the loan will be completely made whole and our contract gets extra funds too + uint256 tokensToTakeFromSender = abs(minAmountDifference); + + + + uint256 liquidationProtocolFee = Math.mulDiv( + tokensToTakeFromSender , + ISmartCommitmentForwarder(SMART_COMMITMENT_FORWARDER) + .getLiquidationProtocolFeePercent(), + 10000) ; + + + IERC20(principalToken).safeTransferFrom( + msg.sender, + address(this), + principalDue + tokensToTakeFromSender - liquidationProtocolFee + ); + + address protocolFeeRecipient = ITellerV2(address(TELLER_V2)).getProtocolFeeRecipient(); + + if (liquidationProtocolFee > 0) { + IERC20(principalToken).safeTransferFrom( + msg.sender, + address(protocolFeeRecipient), + liquidationProtocolFee + ); + } + + totalPrincipalTokensRepaid += principalDue; + + + tokenDifferenceFromLiquidations += int256(tokensToTakeFromSender - liquidationProtocolFee ); + + + } else { + + + uint256 tokensToGiveToSender = abs(minAmountDifference); + + + + //dont stipend/refund more than principalDue base + if (tokensToGiveToSender > principalDue) { + tokensToGiveToSender = principalDue; + } + + uint256 netAmountDue = principalDue - tokensToGiveToSender ; + + + if (netAmountDue > 0) { + IERC20(principalToken).safeTransferFrom( + msg.sender, + address(this), + netAmountDue //principalDue - tokensToGiveToSender + ); + } + + totalPrincipalTokensRepaid += principalDue; + + tokenDifferenceFromLiquidations -= int256(tokensToGiveToSender); + + + + } + + //this will effectively 'forfeit' tokens from this contract equal to the amount (principal) that has not been repaid ! principalDue + //this will give collateral to the caller + ITellerV2(TELLER_V2).lenderCloseLoanWithRecipient(_bidId, msg.sender); + + + emit DefaultedLoanLiquidated( + _bidId, + msg.sender, + principalDue, + _tokenAmountDifference + ); + } + + + /** + * @notice Returns the timestamp when the contract was last unpaused + * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder + * @dev This accounts for pauses from both this contract and the forwarder + * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause + */ + function getLastUnpausedAt() + public view + returns (uint256) { + + + return Math.max( + lastUnpausedAt, + IPausableTimestamp(SMART_COMMITMENT_FORWARDER).getLastUnpausedAt() //this counts tellerV2 pausing + ) + ; + + + } + + + /** + * @notice Sets the lastUnpausedAt timestamp to the current block timestamp + * @dev Called internally when the contract is unpaused + * @dev This timestamp is used to calculate valid liquidation windows after unpausing + */ + function setLastUnpausedAt() internal { + lastUnpausedAt = block.timestamp; + } + + + /** + * @notice Gets the total principal amount of a loan + * @dev Retrieves loan details from the TellerV2 contract + * @param _bidId The unique identifier of the loan bid + * @return principalAmount The total principal amount of the loan + */ + function _getLoanTotalPrincipalAmount(uint256 _bidId ) + internal + view + virtual + returns (uint256 principalAmount) + { + (,,,, principalAmount, , , ) + = ITellerV2(TELLER_V2).getLoanSummary(_bidId); + + + } + + + + /** + * @notice Calculates the amount currently owed for a specific bid + * @dev Calls the TellerV2 contract to calculate the principal and interest due + * @dev Uses the current block.timestamp to calculate up-to-date amounts + * @param _bidId The unique identifier of the loan bid + * @return principal The principal amount currently owed + * @return interest The interest amount currently owed + */ + function _getAmountOwedForBid(uint256 _bidId ) + internal + view + virtual + returns (uint256 principal,uint256 interest) + { + Payment memory owed = ITellerV2(TELLER_V2).calculateAmountOwed(_bidId, block.timestamp ); + + return (owed.principal, owed.interest) ; + } + + + /** + * @notice Returns the cumulative token difference from all liquidations + * @dev This represents the net gain or loss of principal tokens from liquidation events + * @dev Positive values indicate the pool has gained tokens from liquidations + * @dev Negative values indicate the pool has given out tokens as liquidation incentives + * @return The current token difference from all liquidations as a signed integer + */ + function getTokenDifferenceFromLiquidations() public view returns (int256){ + + return tokenDifferenceFromLiquidations; + + } + + + /* + * @dev This function will calculate the incentive amount (using a uniswap bonus plus a timer) + of principal tokens that will be given to incentivize liquidating a loan + + * @dev As time approaches infinite, the output approaches -1 * AmountDue . + */ + function getMinimumAmountDifferenceToCloseDefaultedLoan( + uint256 _amountOwed, + uint256 _loanDefaultedTimestamp + ) public view virtual returns (int256 amountDifference_) { + + require( + _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp, + "LDT" + ); + + uint256 secondsSinceDefaulted = block.timestamp - + _loanDefaultedTimestamp; + + //this starts at 764% and falls to -100% + int256 incentiveMultiplier = int256(86400 - 10000) - + int256(secondsSinceDefaulted); + + if (incentiveMultiplier < -10000) { + incentiveMultiplier = -10000; + } + + amountDifference_ = + (int256(_amountOwed) * incentiveMultiplier) / + int256(10000); + } + + /** + * @notice Calculates the absolute value of an integer + * @dev Utility function to convert a signed integer to its unsigned absolute value + * @param x The signed integer input + * @return The absolute value of x as an unsigned integer + */ + function abs(int x) private pure returns (uint) { + return x >= 0 ? uint(x) : uint(-x); + } + + + function calculateCollateralRequiredToBorrowPrincipal( + uint256 _principalAmount + ) public + view + virtual + returns (uint256) { + + uint256 baseAmount = calculateCollateralTokensAmountEquivalentToPrincipalTokens( + _principalAmount + ); + + //this is an amount of collateral + return baseAmount.percent(collateralRatio); + } + + /* + * @dev this is expanded by 10e18 + * @dev this logic is very similar to that used in LCFA + */ + function calculateCollateralTokensAmountEquivalentToPrincipalTokens( + uint256 principalAmount + ) public view virtual returns (uint256 collateralTokensAmountToMatchValue) { + + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); + + + uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 + ? pairPriceWithTwapFromOracle + : Math.min( + pairPriceWithTwapFromOracle, + maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor + ); + + + return + getRequiredCollateral( + principalAmount, + principalPerCollateralAmount + ); + } + + + /** + * @notice Retrieves the price ratio from Uniswap for the given pool routes + * @dev Calls the UniswapPricingLibraryV2 to get TWAP (Time-Weighted Average Price) for the specified routes + * @dev This is a low-level internal function that handles direct Uniswap oracle interaction + * @param poolOracleRoutes Array of pool route configurations to use for price calculation + * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96) + */ + function getUniswapPriceRatioForPoolRoutes( + IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes + ) internal view virtual returns (uint256 ) { + + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); + + + return pairPriceWithTwapFromOracle; + } + + /** + * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices + * @dev Uses Uniswap TWAP and applies any configured maximum limits + * @dev Returns the lesser of the oracle price or the configured maximum (if set) + * @param poolOracleRoutes Array of pool route configurations to use for price calculation + * @return The principal per collateral ratio, expanded by the Uniswap expansion factor + */ + function getPrincipalForCollateralForPoolRoutes( + IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes + ) external view virtual returns (uint256 ) { + + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); + + + uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 + ? pairPriceWithTwapFromOracle + : Math.min( + pairPriceWithTwapFromOracle, + maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor + ); + + + return principalPerCollateralAmount; + } + + + /** + * @notice Calculates the amount of collateral tokens required for a given principal amount + * @dev Converts principal amount to equivalent collateral based on current price ratio + * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral + * @param _principalAmount The amount of principal tokens to be borrowed + * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR) + * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization + */ + function getRequiredCollateral( + uint256 _principalAmount, + uint256 _maxPrincipalPerCollateralAmount + + ) internal view virtual returns (uint256) { + + return + MathUpgradeable.mulDiv( + _principalAmount, + STANDARD_EXPANSION_FACTOR, + _maxPrincipalPerCollateralAmount, + MathUpgradeable.Rounding.Up + ); + } + + + /* + @dev This callback occurs when a TellerV2 repayment happens or when a TellerV2 liquidate happens + @dev lenderCloseLoan does not trigger a repayLoanCallback + @dev It is important that only teller loans for this specific pool can call this + @dev It is important that this function does not revert even if paused since repayments can occur in this case + */ + function repayLoanCallback( + uint256 _bidId, + address repayer, + uint256 principalAmount, + uint256 interestAmount + ) external onlyTellerV2 bidIsActiveForGroup(_bidId) { + + uint256 amountDueRemaining = activeBidsAmountDueRemaining[_bidId]; + + + uint256 principalAmountAppliedToAmountDueRemaining = principalAmount < amountDueRemaining ? + principalAmount : amountDueRemaining; + + + //should never fail due to the above . + activeBidsAmountDueRemaining[_bidId] -= principalAmountAppliedToAmountDueRemaining; + + + totalPrincipalTokensRepaid += principalAmountAppliedToAmountDueRemaining; + totalInterestCollected += interestAmount; + + + uint256 excessiveRepaymentAmount = principalAmount < amountDueRemaining ? + 0 : (principalAmount - amountDueRemaining); + + excessivePrincipalTokensRepaid += excessiveRepaymentAmount; + + + emit LoanRepaid( + _bidId, + repayer, + principalAmount, + interestAmount, + totalPrincipalTokensRepaid, + totalInterestCollected + ); + } + + + + + + /** + * @notice If principal get stuck in the escrow vault for any reason, anyone may + * call this function to move them from that vault in to this contract + * @param _amount Amount of tokens to withdraw + */ + function withdrawFromEscrowVault ( uint256 _amount ) external whenForwarderNotPaused whenNotPaused { + + address _escrowVault = ITellerV2(TELLER_V2).getEscrowVault(); + + IEscrowVault(_escrowVault).withdraw(address(principalToken), _amount ); + + emit WithdrawFromEscrow(_amount); + + } + + + + + + /** + * @notice Sets an optional manual ratio for principal/collateral ratio for borrowers. Only Pool Owner. + * @param _maxPrincipalPerCollateralAmount Price ratio, expanded to support sub-one ratios. + */ + function setMaxPrincipalPerCollateralAmount(uint256 _maxPrincipalPerCollateralAmount) + external + onlyOwner { + maxPrincipalPerCollateralAmount = _maxPrincipalPerCollateralAmount; + } + + + + + /** + * @notice This determines the number of shares you get for depositing principal tokens and the number of principal tokens you receive for burning shares + * @return rate_ The current exchange rate, scaled by the EXCHANGE_RATE_FACTOR. + */ + + function sharesExchangeRate() public view virtual returns (uint256 rate_) { + + + uint256 poolTotalEstimatedValue = getPoolTotalEstimatedValue(); + + if (totalSupply() == 0) { + return EXCHANGE_RATE_EXPANSION_FACTOR; // 1 to 1 for first swap + } + + rate_ = + MathUpgradeable.mulDiv(poolTotalEstimatedValue , + EXCHANGE_RATE_EXPANSION_FACTOR , + totalSupply() ); + } + + function sharesExchangeRateInverse() + public + view + virtual + returns (uint256 rate_) + { + return + (EXCHANGE_RATE_EXPANSION_FACTOR * EXCHANGE_RATE_EXPANSION_FACTOR) / + sharesExchangeRate(); + } + + function getPoolTotalEstimatedValue() + internal + view + returns (uint256 poolTotalEstimatedValue_) + { + + int256 poolTotalEstimatedValueSigned = int256(totalPrincipalTokensCommitted) + + + int256(totalInterestCollected) + int256(tokenDifferenceFromLiquidations) + + int256( excessivePrincipalTokensRepaid ) + - int256( totalPrincipalTokensWithdrawn ) + + ; + + + + //if the poolTotalEstimatedValue_ is less than 0, we treat it as 0. + poolTotalEstimatedValue_ = poolTotalEstimatedValueSigned > int256(0) + ? uint256(poolTotalEstimatedValueSigned) + : 0; + } + + /** + * @notice Converts an amount to its underlying value using a given exchange rate with rounding down + * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users + * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint) + * @param amount The amount to convert (in the source unit) + * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR + * @return value_ The converted value in the target unit, rounded down + */ + function _valueOfUnderlying(uint256 amount, uint256 rate) + internal + pure + returns (uint256 value_) + { + if (rate == 0) { + return 0; + } + + // value_ = MathUpgradeable.mulDiv(amount , EXCHANGE_RATE_EXPANSION_FACTOR , rate ); + + value_ = MathUpgradeable.mulDiv( + amount, + EXCHANGE_RATE_EXPANSION_FACTOR, + rate, + MathUpgradeable.Rounding.Down // Explicitly round down + ); + + + } + + + /** + * @notice Converts an amount to its underlying value using a given exchange rate with rounding up + * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety + * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares) + * @param amount The amount to convert (in the source unit) + * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR + * @return value_ The converted value in the target unit, rounded up + */ + function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate) + internal + pure + returns (uint256 value_) + { + if (rate == 0) { + return 0; + } + + + value_ = MathUpgradeable.mulDiv( + amount, + EXCHANGE_RATE_EXPANSION_FACTOR, + rate, + MathUpgradeable.Rounding.Up // Explicitly round down + ); + + } + + + + + /** + * @notice Calculates the total amount of principal tokens currently lent out in active loans + * @dev Subtracts the total repaid principal from the total lent principal + * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation) + * @return The net amount of principal tokens currently outstanding in active loans + */ + function getTotalPrincipalTokensOutstandingInActiveLoans() + internal + view + returns (uint256) + { + if (totalPrincipalTokensRepaid > totalPrincipalTokensLended) { + return 0; + } + + return totalPrincipalTokensLended - totalPrincipalTokensRepaid; + } + + + + /** + * @notice Returns the address of the collateral token accepted by this pool + * @dev Implements the ISmartCommitment interface requirement + * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility + * @return The address of the ERC20 token used as collateral in this pool + */ + function getCollateralTokenAddress() external view returns (address) { + return address(collateralToken); + } + + + /** + * @notice Returns the type of collateral token supported by this pool + * @dev Implements the ISmartCommitment interface requirement + * @dev This pool only supports ERC20 tokens as collateral + * @return The collateral token type (ERC20) from the CommitmentCollateralType enum + */ + function getCollateralTokenType() + external + view + returns (CommitmentCollateralType) + { + return CommitmentCollateralType.ERC20; + } + + /** + * @notice Returns the Teller V2 market ID associated with this lending pool + * @dev Implements the ISmartCommitment interface requirement + * @dev The market ID is set during contract initialization and cannot be changed + * @return The unique market ID within the Teller V2 protocol + */ + function getMarketId() external view returns (uint256) { + return marketId; + } + + /** + * @notice Returns the maximum allowed duration for loans in this pool + * @dev Implements the ISmartCommitment interface requirement + * @dev This value is set during contract initialization and represents seconds + * @dev Borrowers cannot request loans with durations exceeding this value + * @return The maximum loan duration in seconds + */ + function getMaxLoanDuration() external view returns (uint32) { + return maxLoanDuration; + } + + /** + * @notice Calculates the current utilization ratio of the pool + * @dev The utilization ratio is the percentage of committed funds currently out on loans + * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000 + * @dev Result is capped at 10000 (100%) + * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation + * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%) + */ + function getPoolUtilizationRatio(uint256 activeLoansAmountDelta ) public view returns (uint16) { + + if (getPoolTotalEstimatedValue() == 0) { + return 0; + } + + return uint16( Math.min( + MathUpgradeable.mulDiv( + (getTotalPrincipalTokensOutstandingInActiveLoans() + activeLoansAmountDelta), + 10000 , + getPoolTotalEstimatedValue() ) , + 10000 )); + + } + /** + * @notice Calculates the minimum interest rate based on current pool utilization + * @dev The interest rate scales linearly between lower and upper bounds based on utilization + * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio + * @dev Higher utilization results in higher interest rates to incentivize repayments + * @param amountDelta Additional amount to consider when calculating utilization for this rate + * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%) + */ + function getMinInterestRate(uint256 amountDelta) public view returns (uint16) { + return interestRateLowerBound + + uint16( uint256(interestRateUpperBound-interestRateLowerBound) + .percent(getPoolUtilizationRatio(amountDelta ) + + ) ); + } + + + /** + * @notice Returns the address of the principal token used by this pool + * @dev Implements the ISmartCommitment interface requirement + * @dev The principal token is the asset that lenders deposit and borrowers borrow + * @return The address of the ERC20 token used as principal in this pool + */ + function getPrincipalTokenAddress() external view returns (address) { + return address(principalToken); + } + + + /** + * @notice Calculates the amount of principal tokens available for new loans + * @dev The available amount is limited by the liquidity threshold percentage of the pool + * @dev Formula: min(poolValueThreshold - outstandingLoans, 0) + * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals + * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached + */ + function getPrincipalAmountAvailableToBorrow() + public + view + returns (uint256) + { + + + // Calculate the threshold value once to avoid duplicate calculations + uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent); + + // Get the outstanding loan amount + uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans(); + + // If outstanding loans exceed or equal the threshold, return 0 + if (poolValueThreshold <= outstandingLoans) { + return 0; + } + + // Return the difference between threshold and outstanding loans + return poolValueThreshold - outstandingLoans; + + + + } + + + + /** + * @notice Sets the delay time for withdrawing shares. Only Protocol Owner. + * @param _seconds Delay time in seconds. + */ + function setWithdrawDelayTime(uint256 _seconds) + external + onlyProtocolOwner { + require( _seconds < MAX_WITHDRAW_DELAY_TIME , "WD"); + + withdrawDelayTimeSeconds = _seconds; + } + + + + // ------------------------ Pausing functions ------------ + + + + event Paused(address account); + event Unpaused(address account); + + event PausedBorrowing(address account); + event UnpausedBorrowing(address account); + + event PausedLiquidationAuction(address account); + event UnpausedLiquidationAuction(address account); + + + modifier whenPaused() { + require(paused, "P"); + _; + } + modifier whenNotPaused() { + require(!paused, "P"); + _; + } + + modifier whenBorrowingPaused() { + require(borrowingPaused, "P"); + _; + } + modifier whenBorrowingNotPaused() { + require(!borrowingPaused, "P"); + _; + } + + modifier whenLiquidationAuctionPaused() { + require(liquidationAuctionPaused, "P"); + _; + } + modifier whenLiquidationAuctionNotPaused() { + require(!liquidationAuctionPaused, "P"); + _; + } + + + + function _pause() internal { + paused = true; + emit Paused(_msgSender()); + } + + function _unpause() internal { + paused = false; + emit Unpaused(_msgSender()); + } + + + function _pauseBorrowing() internal { + borrowingPaused = true; + emit PausedBorrowing(_msgSender()); + } + + function _unpauseBorrowing() internal { + borrowingPaused = false; + emit UnpausedBorrowing(_msgSender()); + } + + + function _pauseLiquidationAuction() internal { + liquidationAuctionPaused = true; + emit PausedLiquidationAuction(_msgSender()); + } + + function _unpauseLiquidationAuction() internal { + liquidationAuctionPaused = false; + emit UnpausedLiquidationAuction(_msgSender()); + } + + + + + /** + * @notice Lets the DAO/owner of the protocol pause borrowing + */ + function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused { + _pauseBorrowing(); + } + + /** + * @notice Lets the DAO/owner of the protocol unpause borrowing + */ + function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused { + //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused + _unpauseBorrowing(); + } + + /** + * @notice Lets the DAO/owner of the protocol pause liquidation auctions + */ + function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused { + _pauseLiquidationAuction(); + } + + /** + * @notice Lets the DAO/owner of the protocol unpause liquidation auctions + */ + function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused { + setLastUnpausedAt(); + _unpauseLiquidationAuction(); + } + + + + /** + * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism. + */ + function pausePool() public virtual onlyProtocolPauser whenNotPaused { + _pause(); + } + + /** + * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop. + */ + function unpausePool() public virtual onlyProtocolPauser whenPaused { + setLastUnpausedAt(); + _unpause(); + } + + + + + // ------------------------ ERC4626 functions ------------ + + + + + + + + /*////////////////////////////////////////////////////////////// + DEPOSIT/WITHDRAWAL LOGIC + //////////////////////////////////////////////////////////////*/ + + + function deposit(uint256 assets, address receiver) + public + whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA + virtual + returns (uint256 shares) { + + // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard + require(assets > 0 ); + + + + // Transfer assets from sender to vault + uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this)); + principalToken.safeTransferFrom(msg.sender, address(this), assets); + uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this)); + require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, "TB"); + + + // Calculate shares after transfer + shares = _valueOfUnderlying(assets, sharesExchangeRate()); + + + // Update totals + totalPrincipalTokensCommitted += assets; + + // Mint shares to receiver + mintShares(receiver, shares); + + // Check first deposit conditions + if(!firstDepositMade){ + require(msg.sender == owner(), "FDM"); + require(shares >= 1e6, "IS"); + firstDepositMade = true; + } + + // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver); + emit Deposit( msg.sender,receiver, assets, shares ); + + return shares; + } + + + function mint(uint256 shares, address receiver) + public + whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA + virtual + returns (uint256 assets) { + + // Calculate assets needed for desired shares + assets = previewMint(shares); + require(assets > 0); + + + + // Transfer assets from sender to vault + uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this)); + principalToken.safeTransferFrom(msg.sender, address(this), assets); + uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this)); + require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, "TB"); + + // Update totals + totalPrincipalTokensCommitted += assets; + + // Mint shares to receiver + mintShares(receiver, shares); + + // Check first deposit conditions + if(!firstDepositMade){ + require(msg.sender == owner(), "IC"); + require(shares >= 1e6, "IS"); + firstDepositMade = true; + } + + + emit Deposit( msg.sender,receiver, assets, shares ); + return assets; + } + + + function withdraw( + uint256 assets, + address receiver, + address owner + ) public + whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA + virtual + returns (uint256 shares) { + + // Calculate shares required for desired assets + shares = previewWithdraw(assets); + require(shares > 0); + + + // Check withdrawal delay + uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner); + require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, "SW"); + + require(msg.sender == owner, "UA"); + + // Burn shares from owner + burnShares(owner, shares); + + // Update totals + totalPrincipalTokensWithdrawn += assets; + + // Transfer assets to receiver + principalToken.safeTransfer(receiver, assets); + + + emit Withdraw( + owner, + receiver, + owner, + assets, + shares + ); + + return shares; + } + + + function redeem( + uint256 shares, + address receiver, + address owner + ) public + whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA + virtual + returns (uint256 assets) { + + // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard + require(shares > 0); + + // Calculate assets to receive + assets = _valueOfUnderlying(shares, sharesExchangeRateInverse()); + + require(msg.sender == owner, "UA"); + + // Check withdrawal delay + uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner); + require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, "SR"); + + // Burn shares from owner + burnShares(owner, shares); + + // Update totals + totalPrincipalTokensWithdrawn += assets; + + // Transfer assets to receiver + principalToken.safeTransfer(receiver, assets); + + emit Withdraw( + owner, + receiver, + owner, + assets, + shares + ); + + return assets; + } + + /*////////////////////////////////////////////////////////////// + ACCOUNTING LOGIC + //////////////////////////////////////////////////////////////*/ + + function totalAssets() public view virtual returns (uint256) { + return getPoolTotalEstimatedValue(); + } + + + + + function convertToShares(uint256 assets) public view virtual returns (uint256) { + return _valueOfUnderlying(assets, sharesExchangeRate()); + } + + function convertToAssets(uint256 shares) public view virtual returns (uint256) { + return _valueOfUnderlying(shares, sharesExchangeRateInverse()); + } + + + function previewDeposit(uint256 assets) public view virtual returns (uint256) { + + return _valueOfUnderlying(assets, sharesExchangeRate()); + } + + + function previewMint(uint256 shares) public view virtual returns (uint256) { + + + return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse()); + + + } + + + function previewWithdraw(uint256 assets) public view virtual returns (uint256) { + + + return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ; + + } + + + function previewRedeem(uint256 shares) public view virtual returns (uint256) { + + return _valueOfUnderlying(shares, sharesExchangeRateInverse()); + + } + + /*////////////////////////////////////////////////////////////// + DEPOSIT/WITHDRAWAL LIMIT LOGIC + //////////////////////////////////////////////////////////////*/ + + function maxDeposit(address) public view virtual returns (uint256) { + if (paused) { + return 0; + } + + if(!firstDepositMade && msg.sender != owner()){ + return 0; + } + + + return type(uint256).max; + } + + function maxMint(address) public view virtual returns (uint256) { + if (paused) { + return 0; + } + + if(!firstDepositMade && msg.sender != owner()){ + return 0; + } + + return type(uint256).max; + } + + + function maxWithdraw(address owner) public view virtual returns (uint256) { + if (paused) { + return 0; + } + + uint256 ownerAssets = convertToAssets(balanceOf(owner)); + uint256 availableLiquidity = principalToken.balanceOf(address(this)); + + return Math.min(ownerAssets, availableLiquidity); + } + + + function maxRedeem(address owner) public view virtual returns (uint256) { + if (paused) { + return 0; + } + + uint256 availableShares = balanceOf(owner); + uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner); + + if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) { + return 0; + } + + uint256 availableLiquidity = principalToken.balanceOf(address(this)); + uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity); + + return Math.min(availableShares, maxSharesBasedOnLiquidity); + } + + + function asset() public view returns (address assetTokenAddress) { + + return address(principalToken) ; + } + + + + +} \ No newline at end of file diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index a58b0fa0a..767fe70be 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -28,7 +28,7 @@ contract PriceAdapterUniswapV3 is function registerPriceRoute( - bytes[] route + bytes calldata route ) external returns (bytes32 hash) { @@ -46,7 +46,7 @@ contract PriceAdapterUniswapV3 is function getPrice( bytes32 route , uint256 inAmount - ) external returns (uint256 marketId_) { + ) external returns (uint256 outAmount_) { // lookup the route from the mapping From f45f4e201999032ee2eb662ce16bd4b76b5fe613 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 23 Oct 2025 16:19:52 -0400 Subject: [PATCH 02/46] add --- .../LenderCommitmentGroup_Pool_V3.sol | 76 ++++++++++--------- .../contracts/interfaces/IPriceAdapter.sol | 2 +- .../contracts/libraries/FixedPointQ96.sol | 41 ++++++++++ .../price_adapters/PriceAdapterUniswapV3.sol | 23 ++++-- 4 files changed, 98 insertions(+), 44 deletions(-) create mode 100644 packages/contracts/contracts/libraries/FixedPointQ96.sol diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 6a15189e0..ce909c053 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -26,9 +26,14 @@ import "../../../interfaces/IHasProtocolPausingManager.sol"; import "../../../interfaces/IProtocolPausingManager.sol"; - + import "../../../interfaces/IPriceAdapter.sol"; + import "../../../interfaces/ISmartCommitmentForwarder.sol"; +import {FixedPointQ96} from "../../../libraries/FixedPointQ96.sol"; + + + import "../../../libraries/uniswap/TickMath.sol"; import "../../../libraries/uniswap/FixedPoint96.sol"; import "../../../libraries/uniswap/FullMath.sol"; @@ -55,8 +60,8 @@ import { IPausableTimestamp } from "../../../interfaces/IPausableTimestamp.sol"; import { ILenderCommitmentGroup_V2 } from "../../../interfaces/ILenderCommitmentGroup_V2.sol"; import { Payment } from "../../../TellerV2Storage.sol"; -import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; -import {UniswapPricingLibraryV2} from "../../../libraries/UniswapPricingLibraryV2.sol"; +//import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; +//import {UniswapPricingLibraryV2} from "../../../libraries/UniswapPricingLibraryV2.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; @@ -150,10 +155,13 @@ contract LenderCommitmentGroup_Pool_V2 is bool public firstDepositMade; uint256 public withdrawDelayTimeSeconds; - IUniswapPricingLibrary.PoolRouteConfig[] public poolOracleRoutes; + // IUniswapPricingLibrary.PoolRouteConfig[] public poolOracleRoutes; + + bytes32 public priceRouteHash; + //configured by the owner. If 0 , not used. - uint256 public maxPrincipalPerCollateralAmount; + uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW uint256 public lastUnpausedAt; @@ -162,7 +170,6 @@ contract LenderCommitmentGroup_Pool_V2 is bool public liquidationAuctionPaused; - bytes32 public priceRouteHash; event PoolInitialized( @@ -280,17 +287,16 @@ contract LenderCommitmentGroup_Pool_V2 is /** * @notice Initializes the LenderCommitmentGroup_Smart contract. * @param _commitmentGroupConfig Configuration for the commitment group (lending pool). - * @param _poolOracleRoutes Route configuration for the principal/collateral oracle. + * @param _priceAdapterRoute Route configuration for the principal/collateral oracle. */ function initialize( CommitmentGroupConfig calldata _commitmentGroupConfig, - bytes calldata _priceAdapterRoute, + bytes calldata _priceAdapterRoute - //IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes - + ) external initializer { __Ownable_init(); @@ -325,16 +331,12 @@ contract LenderCommitmentGroup_Pool_V2 is require( liquidityThresholdPercent <= 10000, "ILTP"); - for (uint256 i = 0; i < _poolOracleRoutes.length; i++) { - poolOracleRoutes.push(_poolOracleRoutes[i]); - } - - - // require(poolOracleRoutes.length >= 1 && poolOracleRoutes.length <= 2, "PRL"); - + + + //internally this does checks and might revert // we register the price route with the adapter and save it locally - priceRouteHash = IPriceAdapter( _priceAdapter ).registerPriceRoute( + priceRouteHash = IPriceAdapter( PRICE_ADAPTER ).registerPriceRoute( _priceAdapterRoute ); @@ -712,23 +714,26 @@ contract LenderCommitmentGroup_Pool_V2 is function calculateCollateralTokensAmountEquivalentToPrincipalTokens( uint256 principalAmount ) public view virtual returns (uint256 collateralTokensAmountToMatchValue) { - - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 - .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); + + + + // principalPerCollateralAmount + uint256 priceRatioQ96 = IPriceAdapter( PRICE_ADAPTER ) + .getPriceRatioQ96(priceRouteHash); - uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 + /* uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 ? pairPriceWithTwapFromOracle : Math.min( pairPriceWithTwapFromOracle, maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor - ); + ); */ return getRequiredCollateral( principalAmount, - principalPerCollateralAmount + priceRatioQ96 // principalPerCollateralAmount ); } @@ -740,7 +745,7 @@ contract LenderCommitmentGroup_Pool_V2 is * @param poolOracleRoutes Array of pool route configurations to use for price calculation * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96) */ - function getUniswapPriceRatioForPoolRoutes( + /* function getUniswapPriceRatioForPoolRoutes( IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes ) internal view virtual returns (uint256 ) { @@ -749,7 +754,7 @@ contract LenderCommitmentGroup_Pool_V2 is return pairPriceWithTwapFromOracle; - } + } */ /** * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices @@ -758,8 +763,10 @@ contract LenderCommitmentGroup_Pool_V2 is * @param poolOracleRoutes Array of pool route configurations to use for price calculation * @return The principal per collateral ratio, expanded by the Uniswap expansion factor */ + /* // make the price adapter serve this.. ? + function getPrincipalForCollateralForPoolRoutes( - IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes + ) external view virtual returns (uint256 ) { uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 @@ -771,11 +778,10 @@ contract LenderCommitmentGroup_Pool_V2 is : Math.min( pairPriceWithTwapFromOracle, maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor - ); - + ); return principalPerCollateralAmount; - } + } */ /** @@ -783,19 +789,19 @@ contract LenderCommitmentGroup_Pool_V2 is * @dev Converts principal amount to equivalent collateral based on current price ratio * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral * @param _principalAmount The amount of principal tokens to be borrowed - * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR) + * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR) * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization */ function getRequiredCollateral( uint256 _principalAmount, - uint256 _maxPrincipalPerCollateralAmount + uint256 _maxPrincipalPerCollateralAmountQ96 ) internal view virtual returns (uint256) { return MathUpgradeable.mulDiv( _principalAmount, - STANDARD_EXPANSION_FACTOR, + FixedPointQ96.Q96, _maxPrincipalPerCollateralAmount, MathUpgradeable.Rounding.Up ); @@ -873,13 +879,13 @@ contract LenderCommitmentGroup_Pool_V2 is * @notice Sets an optional manual ratio for principal/collateral ratio for borrowers. Only Pool Owner. * @param _maxPrincipalPerCollateralAmount Price ratio, expanded to support sub-one ratios. */ - function setMaxPrincipalPerCollateralAmount(uint256 _maxPrincipalPerCollateralAmount) + /* function setMaxPrincipalPerCollateralAmount(uint256 _maxPrincipalPerCollateralAmount) external onlyOwner { maxPrincipalPerCollateralAmount = _maxPrincipalPerCollateralAmount; } - + */ /** diff --git a/packages/contracts/contracts/interfaces/IPriceAdapter.sol b/packages/contracts/contracts/interfaces/IPriceAdapter.sol index fd54bf5bc..1a7b14d67 100644 --- a/packages/contracts/contracts/interfaces/IPriceAdapter.sol +++ b/packages/contracts/contracts/interfaces/IPriceAdapter.sol @@ -5,5 +5,5 @@ interface IPriceAdapter { function registerPriceRoute(bytes[] route) external returns (bytes32); - function getPrice(bytes32 route, uint256 inAmount) external ; + function getPriceRatioQ96(bytes32 route, uint256 inAmount) external returns( uint256 ); } diff --git a/packages/contracts/contracts/libraries/FixedPointQ96.sol b/packages/contracts/contracts/libraries/FixedPointQ96.sol new file mode 100644 index 000000000..a3b4dbad0 --- /dev/null +++ b/packages/contracts/contracts/libraries/FixedPointQ96.sol @@ -0,0 +1,41 @@ + + + + +//use mul div and make sure we round the proper way ! + + + +/// @title FixedPoint96 +/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) +library FixedPointQ96 { + uint8 constant RESOLUTION = 96; + uint256 constant Q96 = 0x1000000000000000000000000; + + + + // Example: Convert a decimal number (like 0.5) into FixedPoint96 format + function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) { + // The number is scaled by Q96 to convert into fixed point format + return (numerator * FixedPoint96.Q96) / denominator; + } + + // Example: Multiply two fixed-point numbers + function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) { + // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision + return (fixedPointA * fixedPointB) / FixedPoint96.Q96; + } + + // Example: Divide two fixed-point numbers + function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) { + // Divide the two fixed-point numbers and scale back by Q96 to maintain precision + return (fixedPointA * FixedPoint96.Q96) / fixedPointB; + } + + + function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) { + // To convert from Q96 back to normal (human-readable) value, divide by Q96 + return q96Value / FixedPoint96.Q96; + } + +} diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index 767fe70be..437edf817 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -4,11 +4,14 @@ pragma solidity ^0.8.0; // Interfaces -import "./interfaces/IPriceAdapter.sol"; +import "../interfaces/IPriceAdapter.sol"; + +import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; + contract PriceAdapterUniswapV3 is - IPriceAdapter, + IPriceAdapter { @@ -43,16 +46,20 @@ contract PriceAdapterUniswapV3 is } - - function getPrice( - bytes32 route , uint256 inAmount - ) external returns (uint256 outAmount_) { + + + + // can we compress this price ratio? lets compress it with Q96 ! + + function getPriceRatioQ96( + bytes32 route + ) external returns ( uint256 priceRatioQ96 ) { - // lookup the route from the mapping + // lookup the route from the mapping - // use the route to query uniswapV3 for the price using inAmount + // use the route to query uniswapV3 for the price using inAmount From d51a46f039fe15dbd7bfbc5226c9840914f2d7ad Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 23 Oct 2025 16:26:29 -0400 Subject: [PATCH 03/46] poolsv3 compiles w q96 --- .../LenderCommitmentGroup_Pool_V3.sol | 14 +++---- .../interfaces/ILenderCommitmentGroup_V3.sol | 41 +++++++++++++++++++ .../contracts/interfaces/IPriceAdapter.sol | 4 +- .../contracts/libraries/FixedPointQ96.sol | 8 ++-- .../price_adapters/PriceAdapterUniswapV3.sol | 2 +- 5 files changed, 54 insertions(+), 15 deletions(-) create mode 100644 packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index ce909c053..9a01d4bf5 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -57,12 +57,10 @@ import { ILoanRepaymentCallbacks } from "../../../interfaces/ILoanRepaymentCallb import { IEscrowVault } from "../../../interfaces/IEscrowVault.sol"; import { IPausableTimestamp } from "../../../interfaces/IPausableTimestamp.sol"; -import { ILenderCommitmentGroup_V2 } from "../../../interfaces/ILenderCommitmentGroup_V2.sol"; +import { ILenderCommitmentGroup_V3 } from "../../../interfaces/ILenderCommitmentGroup_V3.sol"; import { Payment } from "../../../TellerV2Storage.sol"; -//import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; -//import {UniswapPricingLibraryV2} from "../../../libraries/UniswapPricingLibraryV2.sol"; - + import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; @@ -87,8 +85,8 @@ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */ -contract LenderCommitmentGroup_Pool_V2 is - ILenderCommitmentGroup_V2, +contract LenderCommitmentGroup_Pool_V3 is + ILenderCommitmentGroup_V3, IERC4626, // interface functions for lenders ISmartCommitment, // interface functions for borrowers (teller protocol) ILoanRepaymentListener, @@ -794,7 +792,7 @@ contract LenderCommitmentGroup_Pool_V2 is */ function getRequiredCollateral( uint256 _principalAmount, - uint256 _maxPrincipalPerCollateralAmountQ96 + uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 ) internal view virtual returns (uint256) { @@ -802,7 +800,7 @@ contract LenderCommitmentGroup_Pool_V2 is MathUpgradeable.mulDiv( _principalAmount, FixedPointQ96.Q96, - _maxPrincipalPerCollateralAmount, + _maxPrincipalPerCollateralAmountQ96, MathUpgradeable.Rounding.Up ); } diff --git a/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol b/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol new file mode 100644 index 000000000..b45fbef5e --- /dev/null +++ b/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + + +import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; +interface ILenderCommitmentGroup_V3 { + + + + struct CommitmentGroupConfig { + address principalTokenAddress; + address collateralTokenAddress; + uint256 marketId; + uint32 maxLoanDuration; + uint16 interestRateLowerBound; + uint16 interestRateUpperBound; + uint16 liquidityThresholdPercent; + uint16 collateralRatio; + + } + + + function initialize( + CommitmentGroupConfig calldata _commitmentGroupConfig, + + bytes calldata _priceAdapterRoute + + ) + external + ; + + + + function liquidateDefaultedLoanWithIncentive( + uint256 _bidId, + int256 _tokenAmountDifference + ) external ; + + function getTokenDifferenceFromLiquidations() external view returns (int256); + +} diff --git a/packages/contracts/contracts/interfaces/IPriceAdapter.sol b/packages/contracts/contracts/interfaces/IPriceAdapter.sol index 1a7b14d67..a7be727e7 100644 --- a/packages/contracts/contracts/interfaces/IPriceAdapter.sol +++ b/packages/contracts/contracts/interfaces/IPriceAdapter.sol @@ -3,7 +3,7 @@ pragma solidity >=0.8.0 <0.9.0; interface IPriceAdapter { - function registerPriceRoute(bytes[] route) external returns (bytes32); + function registerPriceRoute(bytes memory route) external returns (bytes32); - function getPriceRatioQ96(bytes32 route, uint256 inAmount) external returns( uint256 ); + function getPriceRatioQ96( bytes32 route ) external view returns( uint256 ); } diff --git a/packages/contracts/contracts/libraries/FixedPointQ96.sol b/packages/contracts/contracts/libraries/FixedPointQ96.sol index a3b4dbad0..16c7d440d 100644 --- a/packages/contracts/contracts/libraries/FixedPointQ96.sol +++ b/packages/contracts/contracts/libraries/FixedPointQ96.sol @@ -17,25 +17,25 @@ library FixedPointQ96 { // Example: Convert a decimal number (like 0.5) into FixedPoint96 format function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) { // The number is scaled by Q96 to convert into fixed point format - return (numerator * FixedPoint96.Q96) / denominator; + return (numerator * Q96) / denominator; } // Example: Multiply two fixed-point numbers function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) { // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision - return (fixedPointA * fixedPointB) / FixedPoint96.Q96; + return (fixedPointA * fixedPointB) / Q96; } // Example: Divide two fixed-point numbers function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) { // Divide the two fixed-point numbers and scale back by Q96 to maintain precision - return (fixedPointA * FixedPoint96.Q96) / fixedPointB; + return (fixedPointA * Q96) / fixedPointB; } function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) { // To convert from Q96 back to normal (human-readable) value, divide by Q96 - return q96Value / FixedPoint96.Q96; + return q96Value / Q96; } } diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index 437edf817..df1f6a5b7 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -53,7 +53,7 @@ contract PriceAdapterUniswapV3 is function getPriceRatioQ96( bytes32 route - ) external returns ( uint256 priceRatioQ96 ) { + ) external view returns ( uint256 priceRatioQ96 ) { // lookup the route from the mapping From 96454e1e6d10b8c41d72119b6dc2850fa5c2477d Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 27 Oct 2025 10:20:58 -0400 Subject: [PATCH 04/46] uniswapv3 price adapter draft --- .../price_adapters/PriceAdapterUniswapV3.sol | 161 ++++++++++++++++-- 1 file changed, 145 insertions(+), 16 deletions(-) diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index df1f6a5b7..8eab479e7 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -5,16 +5,33 @@ pragma solidity ^0.8.0; // Interfaces import "../interfaces/IPriceAdapter.sol"; +import "../interfaces/uniswap/IUniswapV3Pool.sol"; import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; +import {FullMath} from "../libraries/uniswap/FullMath.sol"; +import {TickMath} from "../libraries/uniswap/TickMath.sol"; - contract PriceAdapterUniswapV3 is - IPriceAdapter - + IPriceAdapter + { - + + + + + + struct PoolRoute { + address pool; + bool zeroForOne; + uint32 twapInterval; + uint256 token0Decimals; + uint256 token1Decimals; + } + + + + mapping(bytes32 => bytes) public priceRoutes; @@ -31,38 +48,150 @@ contract PriceAdapterUniswapV3 is function registerPriceRoute( - bytes calldata route + bytes memory route ) external returns (bytes32 hash) { - - - // validate the route for length, other restrictions - - // hash the route with keccak256 + PoolRoute[] memory route_array = decodePoolRoutes( route ); + // hash the route with keccak256 + bytes32 poolRouteHash = keccak256(route); - // store the route by its hash in the priceRoutes mapping + // store the route by its hash in the priceRoutes mapping + priceRoutes[poolRouteHash] = route; + emit RouteRegistered(poolRouteHash, route); + return poolRouteHash; } - // can we compress this price ratio? lets compress it with Q96 ! + // can we compress this price ratio? lets compress it with Q96 ! function getPriceRatioQ96( - bytes32 route + bytes32 route ) external view returns ( uint256 priceRatioQ96 ) { - - // lookup the route from the mapping + // lookup the route from the mapping + bytes memory routeData = priceRoutes[route]; + require(routeData.length > 0, "Route not found"); + + // decode the route + PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData); + + // start with Q96 = 1.0 in Q96 format + priceRatioQ96 = FixedPointQ96.Q96; + + // iterate through each pool and multiply prices + for (uint256 i = 0; i < poolRoutes.length; i++) { + uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]); + // multiply using Q96 arithmetic + priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96); + } + } + + + + // ----- + + + + function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) { + + encoded = abi.encode(routes); + + } + + // validate the route for length, other restrictions + //must be length 1 or 2 - // use the route to query uniswapV3 for the price using inAmount + function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { + route_array = abi.decode(data, (PoolRoute[])); + } + + + + + // ------- + + + + function getUniswapPriceRatioForPool( + PoolRoute memory _poolRoute + ) internal view returns (uint256 priceRatioQ96) { + // this is expanded by 2**96 + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRoute.pool, + _poolRoute.twapInterval + ); + + // Convert sqrtPriceX96 to priceQ96 + // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format + priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96); + + // If we need the inverse (token0 in terms of token1), invert + bool invert = !_poolRoute.zeroForOne; + if (invert) { + // To invert a Q96 number: (Q96 * Q96) / value + priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96); + } + } + + 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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceQ96) + { + // sqrtPriceX96^2 / 2^96 = priceQ96 + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96); + } + + + + + + + + + + + + + + + + + } From 3a31e11d0c1419f4e45287421aff33dd8b347c34 Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 27 Oct 2025 10:39:56 -0400 Subject: [PATCH 05/46] tests pass for uniswap v3 price adapter --- .../price_adapters/PriceAdapterUniswapV3.sol | 6 +- .../PriceAdapterUniswapV3Test.sol | 381 ++++++++++++++++++ 2 files changed, 385 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/tests/price_adapters/PriceAdapterUniswapV3Test.sol diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index 8eab479e7..d9b350e34 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -104,13 +104,15 @@ contract PriceAdapterUniswapV3 is } - // validate the route for length, other restrictions - //must be length 1 or 2 + // validate the route for length, other restrictions + //must be length 1 or 2 function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { route_array = abi.decode(data, (PoolRoute[])); + require(route_array.length == 1 || route_array.length == 2, "Route must have 1 or 2 pools"); + } diff --git a/packages/contracts/tests/price_adapters/PriceAdapterUniswapV3Test.sol b/packages/contracts/tests/price_adapters/PriceAdapterUniswapV3Test.sol new file mode 100644 index 000000000..5536999d1 --- /dev/null +++ b/packages/contracts/tests/price_adapters/PriceAdapterUniswapV3Test.sol @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Testable } from "../Testable.sol"; +import {PriceAdapterUniswapV3} from "../../contracts/price_adapters/PriceAdapterUniswapV3.sol"; +import { UniswapV3PoolMock } from "../../contracts/mock/uniswap/UniswapV3PoolMock.sol"; +import { FixedPointQ96 } from "../../contracts/libraries/FixedPointQ96.sol"; +import "forge-std/console.sol"; + +contract PriceAdapterUniswapV3Test is Testable { + + PriceAdapterUniswapV3 public adapter; + UniswapV3PoolMock public mockPool1; + UniswapV3PoolMock public mockPool2; + + function setUp() public { + adapter = new PriceAdapterUniswapV3(); + mockPool1 = new UniswapV3PoolMock(); + mockPool2 = new UniswapV3PoolMock(); + } + + // ========== ENCODE/DECODE TESTS ========== + + function test_encodeDecodePoolRoutes_single() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + PriceAdapterUniswapV3.PoolRoute[] memory decoded = adapter.decodePoolRoutes(encoded); + + assertEq(decoded.length, 1, "Decoded length mismatch"); + assertEq(decoded[0].pool, address(mockPool1), "Pool address mismatch"); + assertEq(decoded[0].zeroForOne, true, "zeroForOne mismatch"); + assertEq(decoded[0].twapInterval, 0, "twapInterval mismatch"); + assertEq(decoded[0].token0Decimals, 18, "token0Decimals mismatch"); + assertEq(decoded[0].token1Decimals, 18, "token1Decimals mismatch"); + } + + function test_encodeDecodePoolRoutes_double() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](2); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 6 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: false, + twapInterval: 300, + token0Decimals: 6, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + PriceAdapterUniswapV3.PoolRoute[] memory decoded = adapter.decodePoolRoutes(encoded); + + assertEq(decoded.length, 2, "Decoded length mismatch"); + assertEq(decoded[0].pool, address(mockPool1), "Pool1 address mismatch"); + assertEq(decoded[1].pool, address(mockPool2), "Pool2 address mismatch"); + assertEq(decoded[1].zeroForOne, false, "zeroForOne mismatch"); + assertEq(decoded[1].twapInterval, 300, "twapInterval mismatch"); + } + + function test_decodePoolRoutes_revert_empty() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](0); + bytes memory encoded = adapter.encodePoolRoutes(routes); + + vm.expectRevert("Route must have 1 or 2 pools"); + adapter.decodePoolRoutes(encoded); + } + + function test_decodePoolRoutes_revert_tooMany() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](3); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + routes[2] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + + vm.expectRevert("Route must have 1 or 2 pools"); + adapter.decodePoolRoutes(encoded); + } + + // ========== REGISTER PRICE ROUTE TESTS ========== + + function test_registerPriceRoute_single() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 expectedHash = keccak256(encoded); + + vm.expectEmit(true, true, true, true); + emit IPriceAdapter.RouteRegistered(expectedHash, encoded); + + bytes32 returnedHash = adapter.registerPriceRoute(encoded); + + assertEq(returnedHash, expectedHash, "Hash mismatch"); + + // Verify route is stored + bytes memory storedRoute = adapter.priceRoutes(expectedHash); + assertEq(storedRoute, encoded, "Stored route mismatch"); + } + + function test_registerPriceRoute_double() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](2); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 6 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: false, + twapInterval: 0, + token0Decimals: 6, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + assertTrue(hash != bytes32(0), "Hash should not be zero"); + + bytes memory storedRoute = adapter.priceRoutes(hash); + assertEq(storedRoute, encoded, "Stored route mismatch"); + } + + function test_registerPriceRoute_revert_invalid() public { + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](3); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + routes[2] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + + vm.expectRevert("Route must have 1 or 2 pools"); + adapter.registerPriceRoute(encoded); + } + + // ========== GET PRICE RATIO TESTS ========== + + function test_getPriceRatioQ96_single_equalPrice() public { + // Set up pool with price = 1.0 (sqrtPriceX96 = 2^96) + mockPool1.set_mockSqrtPriceX96(uint160(2**96)); + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // Price should be 1.0 in Q96 format + assertEq(priceRatioQ96, FixedPointQ96.Q96, "Price should be Q96 for 1:1 ratio"); + } + + function test_getPriceRatioQ96_single_highPrice() public { + // Set up pool with a high price + // For price = 100, sqrtPrice = 10, so sqrtPriceX96 = 10 * 2^96 + uint160 sqrtPriceX96 = uint160(10 * uint256(2**96)); + mockPool1.set_mockSqrtPriceX96(sqrtPriceX96); + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // Price should be 100 * Q96 (price = 100.0) + uint256 expectedPrice = 100 * FixedPointQ96.Q96; + assertEq(priceRatioQ96, expectedPrice, "Price should be 100.0 in Q96"); + } + + function test_getPriceRatioQ96_single_invertedPrice() public { + // Set up pool with price = 1.0, but inverted + mockPool1.set_mockSqrtPriceX96(uint160(2**96)); + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: false, // inverted + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // When inverted, price of 1.0 should still be 1.0 + assertEq(priceRatioQ96, FixedPointQ96.Q96, "Inverted price of 1.0 should still be Q96"); + } + + function test_getPriceRatioQ96_double_equalPrices() public { + // Both pools with price = 1.0 + mockPool1.set_mockSqrtPriceX96(uint160(2**96)); + mockPool2.set_mockSqrtPriceX96(uint160(2**96)); + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](2); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 6 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 6, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // 1.0 * 1.0 = 1.0 + assertEq(priceRatioQ96, FixedPointQ96.Q96, "Combined price should be Q96"); + } + + function test_getPriceRatioQ96_double_multipliedPrices() public { + // Pool1: price = 4.0 (sqrtPrice = 2 * 2^96) + // Pool2: price = 0.25 (sqrtPrice = 0.5 * 2^96) + // Combined: 4.0 * 0.25 = 1.0 + + mockPool1.set_mockSqrtPriceX96(uint160(2 * 2**96)); + mockPool2.set_mockSqrtPriceX96(uint160(2**95)); // 0.5 * 2^96 + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](2); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 6 + }); + routes[1] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool2), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 6, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // 4.0 * 0.25 = 1.0 + assertEq(priceRatioQ96, FixedPointQ96.Q96, "Combined price should be Q96"); + } + + function test_getPriceRatioQ96_revert_routeNotFound() public { + bytes32 nonExistentHash = keccak256("nonexistent"); + + vm.expectRevert("Route not found"); + adapter.getPriceRatioQ96(nonExistentHash); + } + + // ========== Q96 ARITHMETIC VERIFICATION TESTS ========== + + function test_Q96_multiplication_preservesPrecision() public { + // Set up a known price: sqrt(2) * 2^96 ≈ 1.414 price ratio + // Calculate: 2^96 * 141421356 / 100000000 + // To avoid overflow, do: (2^96 / 100000000) * 141421356 + uint256 q96 = uint256(2**96); + uint160 sqrtPriceX96 = uint160((q96 * 141421356) / 100000000); // ~sqrt(2) + mockPool1.set_mockSqrtPriceX96(sqrtPriceX96); + + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: address(mockPool1), + zeroForOne: true, + twapInterval: 0, + token0Decimals: 18, + token1Decimals: 18 + }); + + bytes memory encoded = adapter.encodePoolRoutes(routes); + bytes32 hash = adapter.registerPriceRoute(encoded); + + uint256 priceRatioQ96 = adapter.getPriceRatioQ96(hash); + + // Verify it's in Q96 format (should be around 2 * Q96 for sqrt(2)^2) + uint256 expectedPrice = 2 * FixedPointQ96.Q96; // sqrt(2)^2 = 2 + + // Allow for small rounding error (within 0.1%) + uint256 diff = priceRatioQ96 > expectedPrice ? priceRatioQ96 - expectedPrice : expectedPrice - priceRatioQ96; + assertLt(diff, expectedPrice / 1000, "Price should be close to 2.0 in Q96"); + } + + function test_Q96_conversion_fromFixedPoint() public { + // Test that we can convert Q96 values back to human-readable format + uint256 oneInQ96 = FixedPointQ96.Q96; + uint256 twoInQ96 = 2 * FixedPointQ96.Q96; + uint256 halfInQ96 = FixedPointQ96.Q96 / 2; + + assertEq(FixedPointQ96.fromFixedPoint96(oneInQ96), 1, "1.0 in Q96 should convert to 1"); + assertEq(FixedPointQ96.fromFixedPoint96(twoInQ96), 2, "2.0 in Q96 should convert to 2"); + assertEq(FixedPointQ96.fromFixedPoint96(halfInQ96), 0, "0.5 in Q96 should convert to 0 (integer division)"); + } +} + +// Need to add event declaration for testing +interface IPriceAdapter { + event RouteRegistered(bytes32 hash, bytes route); +} From b9f015975141abb5a27d726232002b634018aa91 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 28 Oct 2025 12:25:15 -0400 Subject: [PATCH 06/46] add to uniswap v4 state view --- .../LenderCommitmentGroup_Pool_V3.sol | 5 +- .../interfaces/uniswap/IUniswapV4Pool.sol | 24 ++ .../interfaces/uniswapv4/IStateView.sol | 133 +++++++++++ .../price_adapters/PriceAdapterUniswapV3.sol | 9 +- .../price_adapters/PriceAdapterUniswapV4.sol | 211 ++++++++++++++++++ 5 files changed, 374 insertions(+), 8 deletions(-) create mode 100644 packages/contracts/contracts/interfaces/uniswap/IUniswapV4Pool.sol create mode 100644 packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol create mode 100644 packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 9a01d4bf5..98b17de5e 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -100,8 +100,7 @@ contract LenderCommitmentGroup_Pool_V3 is using AddressUpgradeable for address; using NumbersLib for uint256; - uint256 public immutable STANDARD_EXPANSION_FACTOR = 1e18; - + uint256 public immutable MIN_TWAP_INTERVAL = 3; uint256 public immutable UNISWAP_EXPANSION_FACTOR = 2**96; @@ -787,7 +786,7 @@ contract LenderCommitmentGroup_Pool_V3 is * @dev Converts principal amount to equivalent collateral based on current price ratio * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral * @param _principalAmount The amount of principal tokens to be borrowed - * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR) + * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96) * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization */ function getRequiredCollateral( diff --git a/packages/contracts/contracts/interfaces/uniswap/IUniswapV4Pool.sol b/packages/contracts/contracts/interfaces/uniswap/IUniswapV4Pool.sol new file mode 100644 index 000000000..cd59c7241 --- /dev/null +++ b/packages/contracts/contracts/interfaces/uniswap/IUniswapV4Pool.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +pragma solidity >=0.5.0; + +import "./pool/IUniswapV3PoolImmutables.sol"; +import "./pool/IUniswapV3PoolState.sol"; +import "./pool/IUniswapV3PoolDerivedState.sol"; +import "./pool/IUniswapV3PoolActions.sol"; +import "./pool/IUniswapV3PoolOwnerActions.sol"; +import "./pool/IUniswapV3PoolEvents.sol"; + +/// @title The interface for a Uniswap V3 Pool +/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform +/// to the ERC20 specification +/// @dev The pool interface is broken up into many smaller pieces +interface IUniswapV4Pool is + IUniswapV3PoolImmutables, + IUniswapV3PoolState, + IUniswapV3PoolDerivedState, + IUniswapV3PoolActions, + IUniswapV3PoolOwnerActions, + IUniswapV3PoolEvents +{ + +} diff --git a/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol b/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol new file mode 100644 index 000000000..70e3e574d --- /dev/null +++ b/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; +import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; +import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; +import {Position} from "@uniswap/v4-core/src/libraries/Position.sol"; +import {IImmutableState} from "../interfaces/IImmutableState.sol"; + +/// @title IStateView +/// @notice Interface for the StateView contract +interface IStateView is IImmutableState { + /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee + /// @dev Corresponds to pools[poolId].slot0 + /// @param poolId The ID of the pool. + /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision. + /// @return tick The current tick of the pool. + /// @return protocolFee The protocol fee of the pool. + /// @return lpFee The swap fee of the pool. + function getSlot0(PoolId poolId) + external + view + returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee); + + /// @notice Retrieves the tick information of a pool at a specific tick. + /// @dev Corresponds to pools[poolId].ticks[tick] + /// @param poolId The ID of the pool. + /// @param tick The tick to retrieve information for. + /// @return liquidityGross The total position liquidity that references this tick + /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) + /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) + /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) + function getTickInfo(PoolId poolId, int24 tick) + external + view + returns ( + uint128 liquidityGross, + int128 liquidityNet, + uint256 feeGrowthOutside0X128, + uint256 feeGrowthOutside1X128 + ); + + /// @notice Retrieves the liquidity information of a pool at a specific tick. + /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo + /// @param poolId The ID of the pool. + /// @param tick The tick to retrieve liquidity for. + /// @return liquidityGross The total position liquidity that references this tick + /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) + function getTickLiquidity(PoolId poolId, int24 tick) + external + view + returns (uint128 liquidityGross, int128 liquidityNet); + + /// @notice Retrieves the fee growth outside a tick range of a pool + /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo + /// @param poolId The ID of the pool. + /// @param tick The tick to retrieve fee growth for. + /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) + /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) + function getTickFeeGrowthOutside(PoolId poolId, int24 tick) + external + view + returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128); + + /// @notice Retrieves the global fee growth of a pool. + /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128 + /// @param poolId The ID of the pool. + /// @return feeGrowthGlobal0 The global fee growth for token0. + /// @return feeGrowthGlobal1 The global fee growth for token1. + function getFeeGrowthGlobals(PoolId poolId) + external + view + returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1); + + /// @notice Retrieves the total liquidity of a pool. + /// @dev Corresponds to pools[poolId].liquidity + /// @param poolId The ID of the pool. + /// @return liquidity The liquidity of the pool. + function getLiquidity(PoolId poolId) external view returns (uint128 liquidity); + + /// @notice Retrieves the tick bitmap of a pool at a specific tick. + /// @dev Corresponds to pools[poolId].tickBitmap[tick] + /// @param poolId The ID of the pool. + /// @param tick The tick to retrieve the bitmap for. + /// @return tickBitmap The bitmap of the tick. + function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap); + + /// @notice Retrieves the position info without needing to calculate the `positionId`. + /// @dev Corresponds to pools[poolId].positions[positionId] + /// @param poolId The ID of the pool. + /// @param owner The owner of the liquidity position. + /// @param tickLower The lower tick of the liquidity range. + /// @param tickUpper The upper tick of the liquidity range. + /// @param salt The bytes32 randomness to further distinguish position state. + /// @return liquidity The liquidity of the position. + /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0. + /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1. + function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) + external + view + returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128); + + /// @notice Retrieves the position information of a pool at a specific position ID. + /// @dev Corresponds to pools[poolId].positions[positionId] + /// @param poolId The ID of the pool. + /// @param positionId The ID of the position. + /// @return liquidity The liquidity of the position. + /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0. + /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1. + function getPositionInfo(PoolId poolId, bytes32 positionId) + external + view + returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128); + + /// @notice Retrieves the liquidity of a position. + /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo + /// @param poolId The ID of the pool. + /// @param positionId The ID of the position. + /// @return liquidity The liquidity of the position. + function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity); + + /// @notice Calculate the fee growth inside a tick range of a pool + /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside + /// @param poolId The ID of the pool. + /// @param tickLower The lower tick of the range. + /// @param tickUpper The upper tick of the range. + /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0. + /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1. + function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper) + external + view + returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128); +} \ No newline at end of file diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index d9b350e34..00eddd9e4 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -36,8 +36,8 @@ contract PriceAdapterUniswapV3 is mapping(bytes32 => bytes) public priceRoutes; - /* Modifiers */ - + + /* Events */ @@ -67,7 +67,6 @@ contract PriceAdapterUniswapV3 is - // can we compress this price ratio? lets compress it with Q96 ! function getPriceRatioQ96( bytes32 route @@ -93,7 +92,7 @@ contract PriceAdapterUniswapV3 is - // ----- + // ------- @@ -118,7 +117,7 @@ contract PriceAdapterUniswapV3 is - // ------- + // ------- diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol new file mode 100644 index 000000000..9df467956 --- /dev/null +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/* + + see https://docs.uniswap.org/contracts/v4/deployments +*/ + + +// Interfaces +import "../interfaces/IPriceAdapter.sol"; + +import {IStateView} from "../interfaces/uniswapv4/IStateView.sol"; + +import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; +import {FullMath} from "../libraries/uniswap/FullMath.sol"; +import {TickMath} from "../libraries/uniswap/TickMath.sol"; + + +contract PriceAdapterUniswapV4 is + IPriceAdapter + +{ + // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet + address immutable UNISWAP_V4_STATE_VIEW; + + struct PoolRoute { + address pool; + bool zeroForOne; + uint32 twapInterval; + uint256 token0Decimals; + uint256 token1Decimals; + } + + + + constructor (address _uniswapStateView ) { + + + UNISWAP_V4_STATE_VIEW = _uniswapStateView; + + } + + + + + mapping(bytes32 => bytes) public priceRoutes; + + + + + /* Events */ + + event RouteRegistered(bytes32 hash, bytes route); + + + /* External Functions */ + + + function registerPriceRoute( + bytes memory route + ) external returns (bytes32 hash) { + + PoolRoute[] memory route_array = decodePoolRoutes( route ); + + // hash the route with keccak256 + bytes32 poolRouteHash = keccak256(route); + + // store the route by its hash in the priceRoutes mapping + priceRoutes[poolRouteHash] = route; + + emit RouteRegistered(poolRouteHash, route); + + return poolRouteHash; + } + + + + + + function getPriceRatioQ96( + bytes32 route + ) external view returns ( uint256 priceRatioQ96 ) { + + // lookup the route from the mapping + bytes memory routeData = priceRoutes[route]; + require(routeData.length > 0, "Route not found"); + + // decode the route + PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData); + + // start with Q96 = 1.0 in Q96 format + priceRatioQ96 = FixedPointQ96.Q96; + + // iterate through each pool and multiply prices + for (uint256 i = 0; i < poolRoutes.length; i++) { + uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]); + // multiply using Q96 arithmetic + priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96); + } + } + + + + // ------- + + + + function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) { + + encoded = abi.encode(routes); + + } + + + // validate the route for length, other restrictions + //must be length 1 or 2 + + function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { + + route_array = abi.decode(data, (PoolRoute[])); + + require(route_array.length == 1 || route_array.length == 2, "Route must have 1 or 2 pools"); + + } + + + + + // ------- + + + + function getUniswapPriceRatioForPool( + PoolRoute memory _poolRoute + ) internal view returns (uint256 priceRatioQ96) { + + // this is expanded by 2**96 + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRoute.pool, + _poolRoute.twapInterval + ); + + // Convert sqrtPriceX96 to priceQ96 + // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format + priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96); + + // If we need the inverse (token0 in terms of token1), invert + bool invert = !_poolRoute.zeroForOne; + if (invert) { + // To invert a Q96 number: (Q96 * Q96) / value + priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96); + } + } + + function getSqrtTwapX96(PoolId poolId, uint32 twapInterval) + internal + view + returns (uint160 sqrtPriceX96) + { + + + + if (twapInterval == 0) { + // return the current price if twapInterval == 0 + (sqrtPriceX96, , , , , , ) = IStateView(poolId).getSlot0(); + } 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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceQ96) + { + // sqrtPriceX96^2 / 2^96 = priceQ96 + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96); + } + + + + + + + + + + + + + + + + + + +} From 33bf5222ecac4b5e157c4b9e13ea0eab10dda7db Mon Sep 17 00:00:00 2001 From: andy Date: Wed, 29 Oct 2025 14:50:31 -0400 Subject: [PATCH 07/46] add dependencies --- .../interfaces/uniswapv4/IImmutableState.sol | 11 +++++++++++ .../contracts/interfaces/uniswapv4/IStateView.sol | 2 +- packages/contracts/package.json | 1 + yarn.lock | 8 ++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 packages/contracts/contracts/interfaces/uniswapv4/IImmutableState.sol diff --git a/packages/contracts/contracts/interfaces/uniswapv4/IImmutableState.sol b/packages/contracts/contracts/interfaces/uniswapv4/IImmutableState.sol new file mode 100644 index 000000000..b968c6d60 --- /dev/null +++ b/packages/contracts/contracts/interfaces/uniswapv4/IImmutableState.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; + +/// @title IImmutableState +/// @notice Interface for the ImmutableState contract +interface IImmutableState { + /// @notice The Uniswap v4 PoolManager contract + function poolManager() external view returns (IPoolManager); +} \ No newline at end of file diff --git a/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol b/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol index 70e3e574d..12ae847c9 100644 --- a/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol +++ b/packages/contracts/contracts/interfaces/uniswapv4/IStateView.sol @@ -5,7 +5,7 @@ import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {Position} from "@uniswap/v4-core/src/libraries/Position.sol"; -import {IImmutableState} from "../interfaces/IImmutableState.sol"; +import {IImmutableState} from "./IImmutableState.sol"; /// @title IStateView /// @notice Interface for the StateView contract diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 9761bce56..21ba4fdbc 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -81,6 +81,7 @@ "@types/semver": "^7.3.9", "@typescript-eslint/eslint-plugin": "^5.5.0", "@typescript-eslint/parser": "^5.5.0", + "@uniswap/v4-core": "1.0.2", "chai": "^4.3.4", "chai-as-promised": "^7.1.1", "chalk": "^4.1.1", diff --git a/yarn.lock b/yarn.lock index 397283aef..4f0529499 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2551,6 +2551,7 @@ __metadata: "@types/semver": ^7.3.9 "@typescript-eslint/eslint-plugin": ^5.5.0 "@typescript-eslint/parser": ^5.5.0 + "@uniswap/v4-core": 1.0.2 chai: ^4.3.4 chai-as-promised: ^7.1.1 chalk: ^4.1.1 @@ -3238,6 +3239,13 @@ __metadata: languageName: node linkType: hard +"@uniswap/v4-core@npm:1.0.2": + version: 1.0.2 + resolution: "@uniswap/v4-core@npm:1.0.2" + checksum: 9dfb3849d7160e94a0ed25025fe51e3b08f9a86361cf322c90003330f8127403021258dc0241a86ceb111e3fd3c2a60290a14ac262310de6360ce30125db4de4 + languageName: node + linkType: hard + "@whatwg-node/events@npm:^0.0.3": version: 0.0.3 resolution: "@whatwg-node/events@npm:0.0.3" From b4f06af88b57e4d971d59306bfa1a0631ad03c6a Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 30 Oct 2025 13:34:09 -0400 Subject: [PATCH 08/46] v4 works with no twap --- .../price_adapters/PriceAdapterUniswapV4.sol | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol index 9df467956..bfb4068e6 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol @@ -8,9 +8,10 @@ pragma solidity ^0.8.0; // Interfaces -import "../interfaces/IPriceAdapter.sol"; +import "../interfaces/IPriceAdapter.sol"; import {IStateView} from "../interfaces/uniswapv4/IStateView.sol"; +import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; import {FullMath} from "../libraries/uniswap/FullMath.sol"; @@ -25,7 +26,7 @@ contract PriceAdapterUniswapV4 is address immutable UNISWAP_V4_STATE_VIEW; struct PoolRoute { - address pool; + PoolId pool; bool zeroForOne; uint32 twapInterval; uint256 token0Decimals; @@ -163,9 +164,13 @@ contract PriceAdapterUniswapV4 is if (twapInterval == 0) { // return the current price if twapInterval == 0 - (sqrtPriceX96, , , , , , ) = IStateView(poolId).getSlot0(); + (sqrtPriceX96, , , ) = IStateView(UNISWAP_V4_STATE_VIEW).getSlot0(poolId); } else { - uint32[] memory secondsAgos = new uint32[](2); + + revert("twap price not impl "); + + + /* uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = twapInterval + 1; // from (before) secondsAgos[1] = 1; // one block prior @@ -178,7 +183,7 @@ contract PriceAdapterUniswapV4 is (tickCumulatives[1] - tickCumulatives[0]) / int32(twapInterval) ) - ); + ); */ } } From 16d7157a69ec655dcdeb03277308b255f95e91e5 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 30 Oct 2025 14:22:53 -0400 Subject: [PATCH 09/46] using recommended library from uniswap docs --- .../price_adapters/PriceAdapterUniswapV4.sol | 54 +++++++++++++++---- packages/contracts/remappings.txt | 6 +++ 2 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 packages/contracts/remappings.txt diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol index bfb4068e6..d92506a67 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol @@ -4,6 +4,12 @@ pragma solidity ^0.8.0; /* see https://docs.uniswap.org/contracts/v4/deployments + + + https://docs.uniswap.org/contracts/v4/guides/read-pool-state + + + */ @@ -11,19 +17,38 @@ pragma solidity ^0.8.0; import "../interfaces/IPriceAdapter.sol"; import {IStateView} from "../interfaces/uniswapv4/IStateView.sol"; -import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; - + import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; import {FullMath} from "../libraries/uniswap/FullMath.sol"; import {TickMath} from "../libraries/uniswap/TickMath.sol"; +import {StateLibrary} from "v4-core/libraries/StateLibrary.sol"; + +import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol"; +import {PoolKey} from "v4-core/types/PoolKey.sol"; +import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol"; + + + contract PriceAdapterUniswapV4 is IPriceAdapter { + + + + using PoolIdLibrary for PoolKey; + + IPoolManager public immutable poolManager; + + + using StateLibrary for IPoolManager; + // address immutable POOL_MANAGER_V4; + + // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet - address immutable UNISWAP_V4_STATE_VIEW; + //address immutable UNISWAP_V4_STATE_VIEW; struct PoolRoute { PoolId pool; @@ -35,15 +60,13 @@ contract PriceAdapterUniswapV4 is - constructor (address _uniswapStateView ) { - - - UNISWAP_V4_STATE_VIEW = _uniswapStateView; - + constructor(IPoolManager _poolManager) { + poolManager = _poolManager; } + mapping(bytes32 => bytes) public priceRoutes; @@ -130,6 +153,17 @@ contract PriceAdapterUniswapV4 is // ------- + function getPoolState(PoolId poolId) internal view returns ( + uint160 sqrtPriceX96, + int24 tick, + uint24 protocolFee, + uint24 lpFee + ) { + return poolManager.getSlot0(poolId); + } + + + function getUniswapPriceRatioForPool( @@ -161,10 +195,10 @@ contract PriceAdapterUniswapV4 is { - + if (twapInterval == 0) { // return the current price if twapInterval == 0 - (sqrtPriceX96, , , ) = IStateView(UNISWAP_V4_STATE_VIEW).getSlot0(poolId); + (sqrtPriceX96, , , ) = getPoolState(poolId); } else { revert("twap price not impl "); diff --git a/packages/contracts/remappings.txt b/packages/contracts/remappings.txt new file mode 100644 index 000000000..e2d6baa4e --- /dev/null +++ b/packages/contracts/remappings.txt @@ -0,0 +1,6 @@ +@ensdomains/=node_modules/@ensdomains/ +@openzeppelin/=node_modules/@openzeppelin/ +ds-test/=lib/forge-std/lib/ds-test/src/ +forge-std/=lib/forge-std/src/ +hardhat/=node_modules/hardhat/ +v4-core/=node_modules/@uniswap/v4-core/src/ From 3e373e8f5823a6a361d332da870c7e1886d62688 Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 3 Nov 2025 15:15:25 -0500 Subject: [PATCH 10/46] add --- .../LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 98b17de5e..7f20e4d83 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -1552,6 +1552,10 @@ contract LenderCommitmentGroup_Pool_V3 is uint256 ownerAssets = convertToAssets(balanceOf(owner)); uint256 availableLiquidity = principalToken.balanceOf(address(this)); + if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) { + return 0; + } + return Math.min(ownerAssets, availableLiquidity); } From 75a3997708037bada66c69722819a95a453bff1f Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 10 Nov 2025 10:51:00 -0500 Subject: [PATCH 11/46] add --- .../price_adapters/PriceAdapterAerodrome.sol | 198 ++++++++++++++++++ .../price_adapters/PriceAdapterUniswapV3.sol | 6 + 2 files changed, 204 insertions(+) create mode 100644 packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol new file mode 100644 index 000000000..d40f54060 --- /dev/null +++ b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + + + +// Interfaces +import "../interfaces/IPriceAdapter.sol"; +import "../interfaces/uniswap/IUniswapV3Pool.sol"; + +import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; +import {FullMath} from "../libraries/uniswap/FullMath.sol"; +import {TickMath} from "../libraries/uniswap/TickMath.sol"; + + +contract PriceAdapterAerodrome is + IPriceAdapter + +{ + + + + + + struct PoolRoute { + address pool; + bool zeroForOne; + uint32 twapInterval; + uint256 token0Decimals; + uint256 token1Decimals; + } + + + + + + + mapping(bytes32 => bytes) public priceRoutes; + + + + + /* Events */ + + event RouteRegistered(bytes32 hash, bytes route); + + + /* External Functions */ + + + function registerPriceRoute( + bytes memory route + ) external returns (bytes32 hash) { + + PoolRoute[] memory route_array = decodePoolRoutes( route ); + + // hash the route with keccak256 + bytes32 poolRouteHash = keccak256(route); + + // store the route by its hash in the priceRoutes mapping + priceRoutes[poolRouteHash] = route; + + emit RouteRegistered(poolRouteHash, route); + + return poolRouteHash; + } + + + + + + function getPriceRatioQ96( + bytes32 route + ) external view returns ( uint256 priceRatioQ96 ) { + + // lookup the route from the mapping + bytes memory routeData = priceRoutes[route]; + require(routeData.length > 0, "Route not found"); + + // decode the route + PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData); + + // start with Q96 = 1.0 in Q96 format + priceRatioQ96 = FixedPointQ96.Q96; + + // iterate through each pool and multiply prices + for (uint256 i = 0; i < poolRoutes.length; i++) { + uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]); + // multiply using Q96 arithmetic + priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96); + } + } + + + + // ------- + + + + function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) { + + encoded = abi.encode(routes); + + } + + + // validate the route for length, other restrictions + //must be length 1 or 2 + + function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { + + route_array = abi.decode(data, (PoolRoute[])); + + require(route_array.length == 1 || route_array.length == 2, "Route must have 1 or 2 pools"); + + } + + + + + // ------- + + + + function getUniswapPriceRatioForPool( + PoolRoute memory _poolRoute + ) internal view returns (uint256 priceRatioQ96) { + + // this is expanded by 2**96 + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRoute.pool, + _poolRoute.twapInterval + ); + + // Convert sqrtPriceX96 to priceQ96 + // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format + priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96); + + // If we need the inverse (token0 in terms of token1), invert + bool invert = !_poolRoute.zeroForOne; + if (invert) { + // To invert a Q96 number: (Q96 * Q96) / value + priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96); + } + } + + 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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceQ96) + { + // sqrtPriceX96^2 / 2^96 = priceQ96 + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96); + } + + + + + + + + + + + + + + + + + + +} diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index 00eddd9e4..98ab5ca2e 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -11,6 +11,12 @@ import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; import {FullMath} from "../libraries/uniswap/FullMath.sol"; import {TickMath} from "../libraries/uniswap/TickMath.sol"; +/* + + This is (typically) compatible with Sushiswap and Aerodrome + +*/ + contract PriceAdapterUniswapV3 is IPriceAdapter From d5a831f976f8c36b40659edd6162a039352e9ef4 Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 10 Nov 2025 11:45:10 -0500 Subject: [PATCH 12/46] add to price adapter aerodrome --- .../interfaces/defi/IAerodromePool.sol | 17 + .../price_adapters/PriceAdapterAerodrome.sol | 78 ++-- .../contracts/tests_fork/PoolsV3_Test.sol | 332 ++++++++++++++++++ 3 files changed, 406 insertions(+), 21 deletions(-) create mode 100644 packages/contracts/contracts/interfaces/defi/IAerodromePool.sol create mode 100644 packages/contracts/tests_fork/PoolsV3_Test.sol diff --git a/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol new file mode 100644 index 000000000..8d5b2f275 --- /dev/null +++ b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol @@ -0,0 +1,17 @@ + // SPDX-License-Identifier: AGPL-3.0 +pragma solidity ^0.8.0; + + + +/** + * @title IPool + * @author Aave + * @notice Defines the basic interface for an Aave Pool. + */ +interface IAerodromePool { + + + function observations(uint256 ticks ) external view returns ( uint256, uint256, uint256 ); + + +} diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol index d40f54060..7240eaf86 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol @@ -5,11 +5,13 @@ pragma solidity ^0.8.0; // Interfaces import "../interfaces/IPriceAdapter.sol"; -import "../interfaces/uniswap/IUniswapV3Pool.sol"; +import "../interfaces/defi/IAerodromePool.sol"; import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; import {FullMath} from "../libraries/uniswap/FullMath.sol"; import {TickMath} from "../libraries/uniswap/TickMath.sol"; + import {FixedPointMathLib} from "../libraries/erc4626/utils/FixedPointMathLib.sol"; + contract PriceAdapterAerodrome is @@ -143,32 +145,66 @@ contract PriceAdapterAerodrome is } } - function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval) + function getSqrtTwapX96(address poolAddress, 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) - ) - ); - } + + + // Get two observations: current and one from twapInterval seconds ago + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = twapInterval + 1 ; // oldest + secondsAgos[1] = 0; // current + + // Fetch observations + (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) = + IAerodromePool(poolAddress).observations(secondsAgos[0]); + + (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) = + IAerodromePool(poolAddress).observations(secondsAgos[1]); + + // Calculate time-weighted average reserves + uint256 timeElapsed = timestamp1 - timestamp0; + require(timeElapsed > 0, "Invalid time elapsed"); + + // Average reserves over the interval + uint256 avgReserve0 = (reserve0Cumulative1 - reserve0Cumulative0) / timeElapsed; + uint256 avgReserve1 = (reserve1Cumulative1 - reserve1Cumulative0) / timeElapsed; + + // Calculate price ratio: token1/token0 + // price = avgReserve1 / avgReserve0 + // sqrtPrice = sqrt(price) = sqrt(avgReserve1 / avgReserve0) + // sqrtPriceX96 = sqrtPrice * 2^96 + + // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 + + sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; + + + + } + + + function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1) + internal + pure + returns (uint160 sqrtPriceX96) + { + + uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1); + uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0); + + sqrtPriceX96 = uint160( + FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0) + ); + + } + + + function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) internal pure diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PoolsV3_Test.sol new file mode 100644 index 000000000..9a43aab08 --- /dev/null +++ b/packages/contracts/tests_fork/PoolsV3_Test.sol @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; + +// Import the PriceAdapterAerodrome contract +import { PriceAdapterAerodrome } from "../contracts/price_adapters/PriceAdapterAerodrome.sol"; +import { IUniswapV3Pool } from "../contracts/interfaces/uniswap/IUniswapV3Pool.sol"; + +/** + * @title PoolsV3_Aerodrome_Fork_Test + * @notice Tests for PriceAdapterAerodrome using a live Aerodrome pool on Base + * @dev This test suite validates the price adapter's functionality with real pool data + */ +contract PoolsV3_Aerodrome_Fork_Test is Test { + + string constant NETWORK_NAME = "base"; + + // Aerodrome pool address on Base with .observe and .slot0 support + address constant AERODROME_POOL = 0x6cDcb1C4A4D1C3C6d054b27AC5B77e89eAFb971d; + + PriceAdapterAerodrome public priceAdapter; + IUniswapV3Pool public pool; + + // Variables to store pool info + address token0; + address token1; + uint8 token0Decimals; + uint8 token1Decimals; + + function setUp() public { + // Fork Base network (Aerodrome is on Base) + // string memory baseRpcUrl = vm.envOr("BASE_RPC_URL", string("https://mainnet.base.org")); + // vm.createSelectFork(baseRpcUrl); + + // Deploy the PriceAdapterAerodrome contract + priceAdapter = new PriceAdapterAerodrome(); + + // Connect to the pool + pool = IUniswapV3Pool(AERODROME_POOL); + + // Verify the pool has code + assertTrue(AERODROME_POOL.code.length > 0, "Pool should have code"); + + // Get token addresses from the pool + token0 = pool.token0(); + token1 = pool.token1(); + + console.log("Pool address:", AERODROME_POOL); + console.log("Token0:", token0); + console.log("Token1:", token1); + + // Get token decimals (would need ERC20 interface to get these properly) + // For now, assuming standard 18 decimals + token0Decimals = 18; + token1Decimals = 18; + } + + /** + * @notice Test that the pool supports slot0() function + * @dev This is required for getting current price without TWAP + */ + function test_pool_has_slot0() public { + ( + uint160 sqrtPriceX96, + int24 tick, + uint16 observationIndex, + uint16 observationCardinality, + uint16 observationCardinalityNext, + uint8 feeProtocol, + bool unlocked + ) = pool.slot0(); + + assertTrue(sqrtPriceX96 > 0, "sqrtPriceX96 should be greater than 0"); + console.log("Current sqrtPriceX96:", sqrtPriceX96); + console.log("Current tick:", uint256(int256(tick))); + console.log("Observation cardinality:", observationCardinality); + } + + /** + * @notice Test that the pool supports observe() function + * @dev This is required for TWAP price calculations + */ + function test_pool_has_observe() public { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = 3600; // 1 hour ago + secondsAgos[1] = 0; // now + + (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = pool.observe(secondsAgos); + + assertEq(tickCumulatives.length, 2, "Should return 2 tick cumulatives"); + assertEq(secondsPerLiquidityCumulativeX128s.length, 2, "Should return 2 liquidity cumulatives"); + + console.log("Tick cumulative (1h ago):", uint256(int256(tickCumulatives[0]))); + console.log("Tick cumulative (now):", uint256(int256(tickCumulatives[1]))); + } + + /** + * @notice Test registering a price route with the Aerodrome pool + */ + function test_register_price_route() public { + // Create a single-hop route (token0 -> token1) + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](1); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + // Encode the route + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + + // Register the route + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + // Verify the route was stored + bytes memory storedRoute = priceAdapter.priceRoutes(routeHash); + assertEq(storedRoute.length, encodedRoute.length, "Route should be stored"); + + console.log("Route hash:"); + console.logBytes32(routeHash); + } + + /** + * @notice Test getting current price (slot0, no TWAP) + * @dev Tests with twapInterval = 0 which uses slot0() + */ + function test_get_current_price_token0_to_token1() public { + // Create route for token0 -> token1 + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](1); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 0, // Use current price via slot0 + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + // Get the price + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + + assertTrue(priceRatioQ96 > 0, "Price should be greater than 0"); + + // Convert Q96 to human readable (divide by 2^96) + uint256 priceQ96Divisor = 2 ** 96; + uint256 priceScaled = (priceRatioQ96 * 1e18) / priceQ96Divisor; + + console.log("Price (token0/token1) Q96:", priceRatioQ96); + console.log("Price (scaled by 1e18):", priceScaled); + } + + /** + * @notice Test getting current price in reverse direction (token1 -> token0) + */ + function test_get_current_price_token1_to_token0() public { + // Create route for token1 -> token0 (inverse) + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](1); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: false, // Inverse direction + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + + assertTrue(priceRatioQ96 > 0, "Price should be greater than 0"); + + uint256 priceQ96Divisor = 2 ** 96; + uint256 priceScaled = (priceRatioQ96 * 1e18) / priceQ96Divisor; + + console.log("Price (token1/token0) Q96:", priceRatioQ96); + console.log("Price (scaled by 1e18):", priceScaled); + } + + /** + * @notice Test getting TWAP price + * @dev Tests with twapInterval > 0 which uses observe() + */ + function test_get_twap_price() public { + // Create route with 1 hour TWAP + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](1); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 3600, // 1 hour TWAP + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + + assertTrue(priceRatioQ96 > 0, "TWAP price should be greater than 0"); + + uint256 priceQ96Divisor = 2 ** 96; + uint256 priceScaled = (priceRatioQ96 * 1e18) / priceQ96Divisor; + + console.log("TWAP Price (1h) Q96:", priceRatioQ96); + console.log("TWAP Price (scaled by 1e18):", priceScaled); + } + + /** + * @notice Test two-hop route (chaining two pools) + * @dev This tests the multi-hop pricing functionality + */ + function test_two_hop_route() public { + // Create a two-hop route using the same pool twice (just for testing) + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](2); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: false, // Go back + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + + assertTrue(priceRatioQ96 > 0, "Two-hop price should be greater than 0"); + + // This should be close to 2^96 (1.0) since we go there and back + uint256 priceQ96Divisor = 2 ** 96; + uint256 priceScaled = (priceRatioQ96 * 1e18) / priceQ96Divisor; + + console.log("Two-hop Price Q96:", priceRatioQ96); + console.log("Two-hop Price (scaled by 1e18):", priceScaled); + console.log("Expected ~1e18 (should be close)"); + } + + /** + * @notice Test that decoding validates route length + */ + function test_decode_rejects_invalid_route_length() public { + // Try to create a route with 3 pools (should fail) + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](3); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = routes[0]; + routes[2] = routes[0]; + + bytes memory encodedRoute = abi.encode(routes); + + vm.expectRevert("Route must have 1 or 2 pools"); + priceAdapter.decodePoolRoutes(encodedRoute); + } + + /** + * @notice Test that getPriceRatioQ96 reverts for unregistered route + */ + function test_get_price_reverts_for_unregistered_route() public { + bytes32 fakeRouteHash = keccak256("fake route"); + + vm.expectRevert("Route not found"); + priceAdapter.getPriceRatioQ96(fakeRouteHash); + } + + /** + * @notice Test price comparison between current and TWAP + */ + function test_compare_current_vs_twap_price() public { + // Get current price + PriceAdapterAerodrome.PoolRoute[] memory currentRoute = new PriceAdapterAerodrome.PoolRoute[](1); + currentRoute[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedCurrentRoute = priceAdapter.encodePoolRoutes(currentRoute); + bytes32 currentRouteHash = priceAdapter.registerPriceRoute(encodedCurrentRoute); + uint256 currentPrice = priceAdapter.getPriceRatioQ96(currentRouteHash); + + // Get TWAP price + PriceAdapterAerodrome.PoolRoute[] memory twapRoute = new PriceAdapterAerodrome.PoolRoute[](1); + twapRoute[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 3600, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedTwapRoute = priceAdapter.encodePoolRoutes(twapRoute); + bytes32 twapRouteHash = priceAdapter.registerPriceRoute(encodedTwapRoute); + uint256 twapPrice = priceAdapter.getPriceRatioQ96(twapRouteHash); + + console.log("Current price Q96:", currentPrice); + console.log("TWAP price Q96:", twapPrice); + + // Both should be positive + assertTrue(currentPrice > 0, "Current price should be positive"); + assertTrue(twapPrice > 0, "TWAP price should be positive"); + + // Calculate percentage difference + uint256 diff = currentPrice > twapPrice + ? currentPrice - twapPrice + : twapPrice - currentPrice; + uint256 percentDiff = (diff * 100) / currentPrice; + + console.log("Percentage difference:", percentDiff, "%"); + } +} From 33ac6439b2dcebf0785e83697bfd0497257f6e5c Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 10 Nov 2025 12:05:58 -0500 Subject: [PATCH 13/46] tests work better --- .../interfaces/defi/IAerodromePool.sol | 18 +++-- ...st.sol => PriceAdapter_Aerodrome_Test.sol} | 67 ++++++++----------- 2 files changed, 37 insertions(+), 48 deletions(-) rename packages/contracts/tests_fork/{PoolsV3_Test.sol => PriceAdapter_Aerodrome_Test.sol} (86%) diff --git a/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol index 8d5b2f275..25ec404bd 100644 --- a/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol +++ b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol @@ -1,17 +1,15 @@ - // SPDX-License-Identifier: AGPL-3.0 +// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.0; - - /** - * @title IPool - * @author Aave - * @notice Defines the basic interface for an Aave Pool. + * @title IAerodromePool + * @notice Defines the basic interface for an Aerodrome Pool. */ interface IAerodromePool { - - - function observations(uint256 ticks ) external view returns ( uint256, uint256, uint256 ); - + function observations(uint256 ticks) external view returns (uint256, uint256, uint256); + + function token0() external view returns (address); + + function token1() external view returns (address); } diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol similarity index 86% rename from packages/contracts/tests_fork/PoolsV3_Test.sol rename to packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol index 9a43aab08..9dff721f0 100644 --- a/packages/contracts/tests_fork/PoolsV3_Test.sol +++ b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol @@ -6,7 +6,7 @@ import "forge-std/console.sol"; // Import the PriceAdapterAerodrome contract import { PriceAdapterAerodrome } from "../contracts/price_adapters/PriceAdapterAerodrome.sol"; -import { IUniswapV3Pool } from "../contracts/interfaces/uniswap/IUniswapV3Pool.sol"; +import { IAerodromePool } from "../contracts/interfaces/defi/IAerodromePool.sol"; /** * @title PoolsV3_Aerodrome_Fork_Test @@ -21,7 +21,7 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { address constant AERODROME_POOL = 0x6cDcb1C4A4D1C3C6d054b27AC5B77e89eAFb971d; PriceAdapterAerodrome public priceAdapter; - IUniswapV3Pool public pool; + IAerodromePool public pool; // Variables to store pool info address token0; @@ -38,7 +38,7 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { priceAdapter = new PriceAdapterAerodrome(); // Connect to the pool - pool = IUniswapV3Pool(AERODROME_POOL); + pool = IAerodromePool(AERODROME_POOL); // Verify the pool has code assertTrue(AERODROME_POOL.code.length > 0, "Pool should have code"); @@ -58,44 +58,35 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { } /** - * @notice Test that the pool supports slot0() function - * @dev This is required for getting current price without TWAP + * @notice Test that the pool has observations data + * @dev This verifies the pool supports observations() for TWAP calculations */ - function test_pool_has_slot0() public { - ( - uint160 sqrtPriceX96, - int24 tick, - uint16 observationIndex, - uint16 observationCardinality, - uint16 observationCardinalityNext, - uint8 feeProtocol, - bool unlocked - ) = pool.slot0(); - - assertTrue(sqrtPriceX96 > 0, "sqrtPriceX96 should be greater than 0"); - console.log("Current sqrtPriceX96:", sqrtPriceX96); - console.log("Current tick:", uint256(int256(tick))); - console.log("Observation cardinality:", observationCardinality); - } - - /** - * @notice Test that the pool supports observe() function - * @dev This is required for TWAP price calculations - */ - function test_pool_has_observe() public { - uint32[] memory secondsAgos = new uint32[](2); - secondsAgos[0] = 3600; // 1 hour ago - secondsAgos[1] = 0; // now - - (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = pool.observe(secondsAgos); - - assertEq(tickCumulatives.length, 2, "Should return 2 tick cumulatives"); - assertEq(secondsPerLiquidityCumulativeX128s.length, 2, "Should return 2 liquidity cumulatives"); - - console.log("Tick cumulative (1h ago):", uint256(int256(tickCumulatives[0]))); - console.log("Tick cumulative (now):", uint256(int256(tickCumulatives[1]))); + function test_pool_has_observations() public { + // Try to get observation at index 0 (most recent) + (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) = + pool.observations(0); + + // Verify we got valid data + assertTrue(timestamp0 > 0, "Timestamp should be greater than 0"); + console.log("Observation 0 - Timestamp:", timestamp0); + console.log("Observation 0 - Reserve0 Cumulative:", reserve0Cumulative0); + console.log("Observation 0 - Reserve1 Cumulative:", reserve1Cumulative0); + + // Try to get observation at index 1 + (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) = + pool.observations(1); + + console.log("Observation 1 - Timestamp:", timestamp1); + console.log("Observation 1 - Reserve0 Cumulative:", reserve0Cumulative1); + console.log("Observation 1 - Reserve1 Cumulative:", reserve1Cumulative1); + + // The cumulative reserves should increase over time, so observation 0 (newer) + // should have higher or equal cumulative values than observation 1 (older) + assertTrue(reserve0Cumulative0 >= reserve0Cumulative1, "Reserve0 cumulative should increase over time"); + assertTrue(reserve1Cumulative0 >= reserve1Cumulative1, "Reserve1 cumulative should increase over time"); } + /** * @notice Test registering a price route with the Aerodrome pool */ From 109f275062d8c43f94c0e115988d800af64317f3 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 13 Nov 2025 15:49:38 -0500 Subject: [PATCH 14/46] tests pass --- .../interfaces/defi/IAerodromePool.sol | 2 + .../price_adapters/PriceAdapterAerodrome.sol | 40 +++++++++++++++---- .../PriceAdapter_Aerodrome_Test.sol | 8 ++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol index 25ec404bd..7429d0d3d 100644 --- a/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol +++ b/packages/contracts/contracts/interfaces/defi/IAerodromePool.sol @@ -6,6 +6,8 @@ pragma solidity ^0.8.0; * @notice Defines the basic interface for an Aerodrome Pool. */ interface IAerodromePool { + function lastObservation() external view returns (uint256, uint256, uint256); + function observationLength() external view returns (uint256 ); function observations(uint256 ticks) external view returns (uint256, uint256, uint256); diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol index 7240eaf86..369539015 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol @@ -151,26 +151,50 @@ contract PriceAdapterAerodrome is returns (uint160 sqrtPriceX96) { + + uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; + + + if (twapInterval == 0 ){ + + //return something different.. + + + + (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) = + IAerodromePool(poolAddress).observations( latestObservationTick -1 ); + + // Average reserves over the interval -- divisor isnt exactly right ? + uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick; + uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick; + + return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; + } + + // Get two observations: current and one from twapInterval seconds ago uint32[] memory secondsAgos = new uint32[](2); - secondsAgos[0] = twapInterval + 1 ; // oldest - secondsAgos[1] = 0; // current + secondsAgos[0] = 0; // current + secondsAgos[1] = twapInterval + 0 ; // oldest + // Fetch observations + + (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) = - IAerodromePool(poolAddress).observations(secondsAgos[0]); + IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]); (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) = - IAerodromePool(poolAddress).observations(secondsAgos[1]); + IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]); // Calculate time-weighted average reserves - uint256 timeElapsed = timestamp1 - timestamp0; + uint256 timeElapsed = timestamp0 - timestamp1 ; require(timeElapsed > 0, "Invalid time elapsed"); - // Average reserves over the interval - uint256 avgReserve0 = (reserve0Cumulative1 - reserve0Cumulative0) / timeElapsed; - uint256 avgReserve1 = (reserve1Cumulative1 - reserve1Cumulative0) / timeElapsed; + // Average reserves over the interval -- divisor isnt exactly right ? + uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick; + uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick; // Calculate price ratio: token1/token0 // price = avgReserve1 / avgReserve0 diff --git a/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol index 9dff721f0..36d769886 100644 --- a/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol +++ b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol @@ -82,8 +82,8 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { // The cumulative reserves should increase over time, so observation 0 (newer) // should have higher or equal cumulative values than observation 1 (older) - assertTrue(reserve0Cumulative0 >= reserve0Cumulative1, "Reserve0 cumulative should increase over time"); - assertTrue(reserve1Cumulative0 >= reserve1Cumulative1, "Reserve1 cumulative should increase over time"); + assertTrue(reserve0Cumulative1 >= reserve0Cumulative0, "Reserve0 cumulative should increase over time"); + assertTrue(reserve1Cumulative1 >= reserve1Cumulative0, "Reserve1 cumulative should increase over time"); } @@ -184,7 +184,7 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { routes[0] = PriceAdapterAerodrome.PoolRoute({ pool: AERODROME_POOL, zeroForOne: true, - twapInterval: 3600, // 1 hour TWAP + twapInterval: 5, // 1 hour TWAP token0Decimals: token0Decimals, token1Decimals: token1Decimals }); @@ -296,7 +296,7 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { twapRoute[0] = PriceAdapterAerodrome.PoolRoute({ pool: AERODROME_POOL, zeroForOne: true, - twapInterval: 3600, + twapInterval: 5, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); From 76436645e1046669d11e2efdd218c75cd692d73f Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 13 Nov 2025 15:51:04 -0500 Subject: [PATCH 15/46] add --- .../price_adapters/PriceAdapterAerodrome.sol | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol index 369539015..62802f5fa 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterAerodrome.sol @@ -156,9 +156,6 @@ contract PriceAdapterAerodrome is if (twapInterval == 0 ){ - - //return something different.. - (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) = @@ -195,14 +192,9 @@ contract PriceAdapterAerodrome is // Average reserves over the interval -- divisor isnt exactly right ? uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick; uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick; - - // Calculate price ratio: token1/token0 - // price = avgReserve1 / avgReserve0 - // sqrtPrice = sqrt(price) = sqrt(avgReserve1 / avgReserve0) - // sqrtPriceX96 = sqrtPrice * 2^96 - - // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 - + + + // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; From bb07ae25d65c54898dafc090c3c7bd30d29e12a7 Mon Sep 17 00:00:00 2001 From: andy Date: Sun, 16 Nov 2025 19:49:39 -0500 Subject: [PATCH 16/46] add to test --- .../contracts/tests_fork/PoolsV3_Test.sol | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 packages/contracts/tests_fork/PoolsV3_Test.sol diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PoolsV3_Test.sol new file mode 100644 index 000000000..bd502379e --- /dev/null +++ b/packages/contracts/tests_fork/PoolsV3_Test.sol @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + + +// Import your actual contracts +import { TellerV2 } from "../contracts/TellerV2.sol"; +import { SwapRolloverLoan } from "../contracts/LenderCommitmentForwarder/extensions/rollover/SwapRolloverLoan.sol"; +import { SwapRolloverLoan_G1 } from "../contracts/LenderCommitmentForwarder/extensions/rollover/SwapRolloverLoan_G1.sol"; +import { SwapRolloverLoan_G2 } from "../contracts/LenderCommitmentForwarder/extensions/rollover/SwapRolloverLoan_G2.sol"; + +import { MockSwapRolloverLoan } from "../contracts/mock/SwapRolloverLoanMock.sol"; +import { LenderCommitmentGroupFactory_V2 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol"; +import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommitmentGroup_V2.sol"; + + + +import { UniswapPricingHelper } from "../contracts/price_oracles/UniswapPricingHelper.sol"; + +import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; + +import { LenderCommitmentGroup_Pool_V3 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol"; +import { SmartCommitmentForwarder } from "../contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol"; + +/* + +Borrow from pool + +45700000000000001n +“0xbc1d2Ed14128Cd7Af450319b642Fd43d65E495dc”, +“0" +“0x5555555555555555555555555555555555555555” +“0xd1174957123b9645d7e95d5e0b93ebeb729ff67f” +“604800” +6511 +967446n + + +*/ + +contract DeployPool_Fork_Test is Test { + + string constant NETWORK_NAME = "mainnet"; + + SmartCommitmentForwarder scf; + + LenderCommitmentGroup_Pool_V3 pool; + + PriceAdapterUniswapV3 price_adapter ; + + + + using stdJson for string; + + function getDeployedAddress( string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + + + function setUp() public { + + price_adapter = new PriceAdapterUniswapV3() ; + } + +/* + function setUp() public { + address payable scfAddr = payable( getDeployedAddress("SmartCommitmentForwarder") ); + scf = SmartCommitmentForwarder( scfAddr ); + + assertTrue(scfAddr.code.length > 0, "could not connect to scf contract ") ; + + + address payable poolAddr = payable( 0xd1174957123B9645d7E95d5e0b93ebeb729Ff67f ); + pool = LenderCommitmentGroup_Pool_V2(poolAddr); + + assertTrue(poolAddr.code.length > 0, "could not connect to pool contract ") ; + } + */ + + + + + +/* + + Test the UniswapV3 Price oracle for the MOG pool + + 0x5F610ca9Ff0a0Ad9FbF91B8EB85A892fb0eBC620 + +*/ + + + + function test_pool_v3_price_routes () public { + + + // register the route + + bytes32 routeHash = price_adapter.registerPriceRoute ( + + price_route_bytes + + ); + + + uint256 priceRatioQ96 = price_adapter.getPriceRatioQ96(routeHash) ; + + + + + // query the route + + + + /* + uint256 principalAmount = 967446; + uint256 collateralAmount = 45700000000000001; + address collateralTokenAddress = 0x5555555555555555555555555555555555555555; + address recipient = 0xbc1d2Ed14128Cd7Af450319b642Fd43d65E495dc; + uint16 interestRate = 6511; + uint32 loanDuration = 604800; + + + vm.prank(0xbc1d2Ed14128Cd7Af450319b642Fd43d65E495dc); //andres wallet + uint256 res = scf.acceptSmartCommitmentWithRecipient( + address(pool), + principalAmount, + collateralAmount, + 0, //collateral token id + collateralTokenAddress, + recipient, + interestRate, + loanDuration + ); */ + + } + + + + + function etch_uniswap_pricing_helper() public { + + + + + address pricingHelperAddress = 0x6B38aD36f17dd55bE44217d184DB8A01536aa104; + + + UniswapPricingHelper newPricingHelper = new UniswapPricingHelper( ); + + // Then replace the code at the deployed address + vm.etch( address(pricingHelperAddress) , address(newPricingHelper).code ); + + + } + + + + + + function test_pool_collateral_calc() public { + + + etch_uniswap_pricing_helper(); + + + + + address mog_pool_address = 0x5F610ca9Ff0a0Ad9FbF91B8EB85A892fb0eBC620; + + + uint256 amt = LenderCommitmentGroup_Pool_V2( mog_pool_address ). + calculateCollateralRequiredToBorrowPrincipal( + + 1000000 + ); + + + + + } + + + + + /* + function test_TellerV2State() public { + if (address(tellerV2) != address(0)) { + // Test reading state from deployed contract + try tellerV2.protocolFee() returns (uint16 fee) { + console.log("Protocol fee:", fee); + assertTrue(fee >= 0, "Fee should be non-negative"); + } catch { + console.log("Failed to read protocol fee"); + } + } + } + + function test_TellerV2Interactions() public { + if (address(tellerV2) != address(0)) { + // You can test interactions with existing state + // For example, check if certain markets exist, etc. + } + }*/ +} \ No newline at end of file From fe6119cabd95b5a2d4bb2390af32579d04aaac59 Mon Sep 17 00:00:00 2001 From: andy Date: Sun, 16 Nov 2025 19:53:00 -0500 Subject: [PATCH 17/46] test runs but fails --- .../contracts/tests_fork/PoolsV3_Test.sol | 74 ++++++------------- 1 file changed, 22 insertions(+), 52 deletions(-) diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PoolsV3_Test.sol index bd502379e..3271e0bd4 100644 --- a/packages/contracts/tests_fork/PoolsV3_Test.sol +++ b/packages/contracts/tests_fork/PoolsV3_Test.sol @@ -18,10 +18,9 @@ import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommit -import { UniswapPricingHelper } from "../contracts/price_oracles/UniswapPricingHelper.sol"; - -import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; +import { PriceAdapterUniswapV3 } from "../contracts/price_adapters/PriceAdapterUniswapV3.sol"; + import { LenderCommitmentGroup_Pool_V3 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol"; import { SmartCommitmentForwarder } from "../contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol"; @@ -100,19 +99,34 @@ contract DeployPool_Fork_Test is Test { function test_pool_v3_price_routes () public { + address MOG_POOL = 0x5F610ca9Ff0a0Ad9FbF91B8EB85A892fb0eBC620; + uint256 token0Decimals = 18; + uint256 token1Decimals = 6; + // register the route + PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); + routes[0] = PriceAdapterUniswapV3.PoolRoute({ + pool: MOG_POOL, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = price_adapter.encodePoolRoutes(routes); + bytes32 routeHash = price_adapter.registerPriceRoute ( - price_route_bytes + encodedRoute ); uint256 priceRatioQ96 = price_adapter.getPriceRatioQ96(routeHash) ; - + // query the route @@ -145,7 +159,7 @@ contract DeployPool_Fork_Test is Test { - function etch_uniswap_pricing_helper() public { + /* function etch_uniswap_pricing_helper() public { @@ -159,54 +173,10 @@ contract DeployPool_Fork_Test is Test { vm.etch( address(pricingHelperAddress) , address(newPricingHelper).code ); - } - - - - - - function test_pool_collateral_calc() public { - - - etch_uniswap_pricing_helper(); - + } */ - address mog_pool_address = 0x5F610ca9Ff0a0Ad9FbF91B8EB85A892fb0eBC620; - - uint256 amt = LenderCommitmentGroup_Pool_V2( mog_pool_address ). - calculateCollateralRequiredToBorrowPrincipal( - - 1000000 - ); - - - - - } - - - - - /* - function test_TellerV2State() public { - if (address(tellerV2) != address(0)) { - // Test reading state from deployed contract - try tellerV2.protocolFee() returns (uint16 fee) { - console.log("Protocol fee:", fee); - assertTrue(fee >= 0, "Fee should be non-negative"); - } catch { - console.log("Failed to read protocol fee"); - } - } - } - - function test_TellerV2Interactions() public { - if (address(tellerV2) != address(0)) { - // You can test interactions with existing state - // For example, check if certain markets exist, etc. - } - }*/ + } \ No newline at end of file From 7922ae5ae56c3450fe0333755d64e473fcdf226b Mon Sep 17 00:00:00 2001 From: andy Date: Sun, 16 Nov 2025 19:57:20 -0500 Subject: [PATCH 18/46] test passes --- packages/contracts/tests_fork/PoolsV3_Test.sol | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PoolsV3_Test.sol index 3271e0bd4..9a25d7780 100644 --- a/packages/contracts/tests_fork/PoolsV3_Test.sol +++ b/packages/contracts/tests_fork/PoolsV3_Test.sol @@ -99,9 +99,13 @@ contract DeployPool_Fork_Test is Test { function test_pool_v3_price_routes () public { - address MOG_POOL = 0x5F610ca9Ff0a0Ad9FbF91B8EB85A892fb0eBC620; - uint256 token0Decimals = 18; - uint256 token1Decimals = 6; + + // principal token is USDC + //collateral is MOG + + address MOG_POOL = 0xE7f05308e67C33D1041438aDCbBb4405e6430E62; + uint256 token0Decimals = 6; + uint256 token1Decimals = 18; // register the route @@ -109,7 +113,7 @@ contract DeployPool_Fork_Test is Test { PriceAdapterUniswapV3.PoolRoute[] memory routes = new PriceAdapterUniswapV3.PoolRoute[](1); routes[0] = PriceAdapterUniswapV3.PoolRoute({ pool: MOG_POOL, - zeroForOne: true, + zeroForOne: false, twapInterval: 0, token0Decimals: token0Decimals, token1Decimals: token1Decimals From e0a2170c22c690e421d8ebcdb93104c2f0308448 Mon Sep 17 00:00:00 2001 From: andy Date: Sun, 16 Nov 2025 19:57:46 -0500 Subject: [PATCH 19/46] test pass --- .../contracts/tests_fork/PoolsV3_Test.sol | 26 +------------------ 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/packages/contracts/tests_fork/PoolsV3_Test.sol b/packages/contracts/tests_fork/PoolsV3_Test.sol index 9a25d7780..35aa371af 100644 --- a/packages/contracts/tests_fork/PoolsV3_Test.sol +++ b/packages/contracts/tests_fork/PoolsV3_Test.sol @@ -132,31 +132,7 @@ contract DeployPool_Fork_Test is Test { - - // query the route - - - - /* - uint256 principalAmount = 967446; - uint256 collateralAmount = 45700000000000001; - address collateralTokenAddress = 0x5555555555555555555555555555555555555555; - address recipient = 0xbc1d2Ed14128Cd7Af450319b642Fd43d65E495dc; - uint16 interestRate = 6511; - uint32 loanDuration = 604800; - - - vm.prank(0xbc1d2Ed14128Cd7Af450319b642Fd43d65E495dc); //andres wallet - uint256 res = scf.acceptSmartCommitmentWithRecipient( - address(pool), - principalAmount, - collateralAmount, - 0, //collateral token id - collateralTokenAddress, - recipient, - interestRate, - loanDuration - ); */ + } From e4b5141c6df93ad26ce9095515ee84aa4c47d270 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 17:59:32 -0500 Subject: [PATCH 20/46] v3 deploy scripts --- .../LenderCommitmentGroup_Factory_V3.sol | 140 ++++++++++++++++++ .../lender_commitment_group_v3_beacon.ts | 83 +++++++++++ .../lender_groups_factory_v3.ts | 47 ++++++ 3 files changed, 270 insertions(+) create mode 100644 packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol create mode 100644 packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts create mode 100644 packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol new file mode 100644 index 000000000..6a9a584db --- /dev/null +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// Contracts +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; + +import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +// Interfaces +import "../../../interfaces/ITellerV2.sol"; +import "../../../interfaces/IProtocolFee.sol"; +import "../../../interfaces/ITellerV2Storage.sol"; +import "../../../libraries/NumbersLib.sol"; + +import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; + +import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; + + import { IERC4626 } from "../../../interfaces/IERC4626.sol"; + +import { ILenderCommitmentGroup_V3 } from "../../../interfaces/ILenderCommitmentGroup_V3.sol"; + + +contract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable { + using AddressUpgradeable for address; + using NumbersLib for uint256; + + + //this is the beacon proxy + address public lenderGroupBeacon; + + + + mapping(address => uint256) public deployedLenderGroupContracts; + + event DeployedLenderGroupContract(address indexed groupContract); + + + + /** + * @notice Initializes the factory contract. + * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts. + */ + function initialize(address _lenderGroupBeacon ) + external + initializer + { + lenderGroupBeacon = _lenderGroupBeacon; + + __Ownable_init_unchained(); + } + + + /** + * @notice Deploys a new lender commitment group pool contract. + * @dev The function initializes the deployed contract and optionally adds an initial principal amount. + * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract. + * @param _commitmentGroupConfig Configuration parameters for the lender commitment group. + * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library. + * @return newGroupContract_ Address of the newly deployed group contract. + */ + function deployLenderCommitmentGroupPool( + uint256 _initialPrincipalAmount, + ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig, + IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes + ) external returns ( address ) { + + + BeaconProxy newGroupContract_ = new BeaconProxy( + lenderGroupBeacon, + abi.encodeWithSelector( + ILenderCommitmentGroup_V3.initialize.selector, //this initializes + _commitmentGroupConfig, + _poolOracleRoutes + + ) + ); + + deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ? + emit DeployedLenderGroupContract(address(newGroupContract_)); + + + + //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have . + if (_initialPrincipalAmount > 0) { + _depositPrincipal( + address(newGroupContract_), + _initialPrincipalAmount, + _commitmentGroupConfig.principalTokenAddress + + ); + } + + + //transfer ownership to msg.sender + OwnableUpgradeable(address(newGroupContract_)) + .transferOwnership(msg.sender); + + + return address(newGroupContract_) ; + } + + + /** + * @notice Adds principal tokens to a commitment group. + * @param _newGroupContract The address of the group contract to add principal tokens to. + * @param _initialPrincipalAmount The amount of principal tokens to add. + * @param _principalTokenAddress The address of the principal token contract. + */ + function _depositPrincipal( + address _newGroupContract, + uint256 _initialPrincipalAmount, + address _principalTokenAddress + ) internal returns (uint256) { + + + IERC20(_principalTokenAddress).transferFrom( + msg.sender, + address(this), + _initialPrincipalAmount + ); + IERC20(_principalTokenAddress).approve( + _newGroupContract, + _initialPrincipalAmount + ); + + address sharesRecipient = msg.sender; + + uint256 sharesAmount_ = IERC4626( address(_newGroupContract) ) + .deposit( + _initialPrincipalAmount, + sharesRecipient + ); + + return sharesAmount_; + } + +} diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts new file mode 100644 index 000000000..a695016f6 --- /dev/null +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts @@ -0,0 +1,83 @@ + + + +import { DeployFunction } from 'hardhat-deploy/dist/types' + +import { UpgradeableBeacon } from 'types/typechain' + +import { get_ecosystem_contract_address } from "../../../../helpers/ecosystem-contracts-lookup" +/* + +This deploys a one-off test contract of the lender commitment group contract ! + +This is not needed for production + +*/ + + +const deployFn: DeployFunction = async (hre) => { + const tellerV2 = await hre.contracts.get('TellerV2') + const SmartCommitmentForwarder = await hre.contracts.get( + 'SmartCommitmentForwarder' + ) + + + const tellerV2Address = await tellerV2.getAddress() + + + // const uniswapPricingLibraryV2 = await hre.contracts.get('UniswapPricingLibraryV2') + + const priceAdapterAddress = await hre.contracts.get('PriceAdapterAerodrome') + + + const smartCommitmentForwarderAddress = + await SmartCommitmentForwarder.getAddress() + + let uniswapV3FactoryAddress = get_ecosystem_contract_address( hre.network.name, "uniswapV3Factory" ) ; + + + const commitmentGroupBeacon = await hre.deployBeacon( + 'LenderCommitmentGroup_Pool_V3', + { + customName: 'LenderCommitmentGroupBeaconV3', + unsafeAllow: ['constructor', 'state-variable-immutable','external-library-linking'], + constructorArgs: [ + tellerV2Address, + smartCommitmentForwarderAddress, + priceAdapterAddress, + ], + + + } + ) + + + //is this necessary ? + //isnt this just an implementation? + // this is necessary so only the protocol timelock can upgrade the beacon proxy + + const { protocolTimelock , protocolOwnerSafe } = await hre.getNamedAccounts() + hre.log('Transferring ownership of CommitmentGroupBeacon to Gnosis Safe...') + await commitmentGroupBeacon.transferOwnership(protocolTimelock) + hre.log('done.') + + return true +} + + + + + +// tags and deployment +deployFn.id = 'lender-commitment-group-beacon-v3:deploy' +deployFn.tags = ['lender-commitment-group-beacon-v3'] +deployFn.dependencies = [ + 'teller-v2:deploy', + 'smart-commitment-forwarder:deploy' + +] + +deployFn.skip = async (hre) => { + return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm'].includes(hre.network.name) +} +export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts new file mode 100644 index 000000000..6f6f43b3f --- /dev/null +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts @@ -0,0 +1,47 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + + + const tellerV2 = await hre.contracts.get('TellerV2') + const SmartCommitmentForwarder = await hre.contracts.get( + 'SmartCommitmentForwarder' + ) + const LenderGroupsBeacon = await hre.contracts.get( + 'LenderCommitmentGroupBeaconV3' + ) + + const LenderGroupsBeaconAddress = + await LenderGroupsBeacon.getAddress() + + + + const lenderGroupsFactory = await hre.deployProxy( + 'LenderCommitmentGroupFactory_V3', + { + unsafeAllow: ['constructor', 'state-variable-immutable'], + + initArgs: [ + LenderGroupsBeaconAddress + ], + + } + ) + + return true +} + +// tags and deployment +deployFn.id = 'lender-commitment-group-factory-v3:deploy' +deployFn.tags = ['lender-commitment-group-factory-v3'] +deployFn.dependencies = [ + 'teller-v2:deploy', + 'teller-v2:init', + 'smart-commitment-forwarder:deploy', + 'lender-commitment-group-beacon-v3:deploy' +] + +deployFn.skip = async (hre) => { + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism' ,'katana','hyperevm'].includes(hre.network.name) +} +export default deployFn \ No newline at end of file From 94fbf66cdd9d23cc1e2556ba9b08217f3e0e5a37 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:09:44 -0500 Subject: [PATCH 21/46] ready to deploy --- .../LenderCommitmentGroup_Pool_V3.sol | 63 +------------------ .../mock/UniswapPricingHelperMock.sol | 4 -- .../price_adapters/PriceAdapterUniswapV4.sol | 10 +-- .../price_oracles/UniswapPricingHelper.sol | 8 --- packages/contracts/hardhat.config.ts | 10 +++ 5 files changed, 18 insertions(+), 77 deletions(-) diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 96b8cf46b..257224879 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -734,52 +734,8 @@ contract LenderCommitmentGroup_Pool_V3 is ); } - - /** - * @notice Retrieves the price ratio from Uniswap for the given pool routes - * @dev Calls the UniswapPricingLibraryV2 to get TWAP (Time-Weighted Average Price) for the specified routes - * @dev This is a low-level internal function that handles direct Uniswap oracle interaction - * @param poolOracleRoutes Array of pool route configurations to use for price calculation - * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96) - */ - /* function getUniswapPriceRatioForPoolRoutes( - IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes - ) internal view virtual returns (uint256 ) { - - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 - .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); - - - return pairPriceWithTwapFromOracle; - } */ - - /** - * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices - * @dev Uses Uniswap TWAP and applies any configured maximum limits - * @dev Returns the lesser of the oracle price or the configured maximum (if set) - * @param poolOracleRoutes Array of pool route configurations to use for price calculation - * @return The principal per collateral ratio, expanded by the Uniswap expansion factor - */ - /* // make the price adapter serve this.. ? - - function getPrincipalForCollateralForPoolRoutes( - - ) external view virtual returns (uint256 ) { - - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 - .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); - - - uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 - ? pairPriceWithTwapFromOracle - : Math.min( - pairPriceWithTwapFromOracle, - maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor - ); - - return principalPerCollateralAmount; - } */ - + + /** * @notice Calculates the amount of collateral tokens required for a given principal amount @@ -869,20 +825,7 @@ contract LenderCommitmentGroup_Pool_V3 is } - - - - /** - * @notice Sets an optional manual ratio for principal/collateral ratio for borrowers. Only Pool Owner. - * @param _maxPrincipalPerCollateralAmount Price ratio, expanded to support sub-one ratios. - */ - /* function setMaxPrincipalPerCollateralAmount(uint256 _maxPrincipalPerCollateralAmount) - external - onlyOwner { - maxPrincipalPerCollateralAmount = _maxPrincipalPerCollateralAmount; - } - - */ + /** diff --git a/packages/contracts/contracts/mock/UniswapPricingHelperMock.sol b/packages/contracts/contracts/mock/UniswapPricingHelperMock.sol index a401a198e..dc3e7b313 100644 --- a/packages/contracts/contracts/mock/UniswapPricingHelperMock.sol +++ b/packages/contracts/contracts/mock/UniswapPricingHelperMock.sol @@ -1,10 +1,6 @@ pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT - -import "forge-std/console.sol"; - - import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol index d92506a67..9f2063211 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV4.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.24; /* @@ -22,11 +22,11 @@ import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; import {FullMath} from "../libraries/uniswap/FullMath.sol"; import {TickMath} from "../libraries/uniswap/TickMath.sol"; -import {StateLibrary} from "v4-core/libraries/StateLibrary.sol"; +import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; -import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol"; -import {PoolKey} from "v4-core/types/PoolKey.sol"; -import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol"; +import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; +import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; +import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol"; diff --git a/packages/contracts/contracts/price_oracles/UniswapPricingHelper.sol b/packages/contracts/contracts/price_oracles/UniswapPricingHelper.sol index 2982346ae..7dd10976a 100644 --- a/packages/contracts/contracts/price_oracles/UniswapPricingHelper.sol +++ b/packages/contracts/contracts/price_oracles/UniswapPricingHelper.sol @@ -1,10 +1,6 @@ pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT - -import "forge-std/console.sol"; - - import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; @@ -52,10 +48,6 @@ contract UniswapPricingHelper ); - console.log("ratio"); - console.logUint(pool0PriceRatio); - console.logUint(pool1PriceRatio); - return FullMath.mulDiv( pool0PriceRatio, diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index 4dc1b65d0..55f4d1928 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -359,6 +359,16 @@ export default { }, }, }, + + { + version: '0.8.24', + settings: { + optimizer: { + enabled: true, // !isTesting, //need this for now due to large size of tellerV2.test + runs: 200, + }, + }, + }, ], }, From d0da1c94947dd02775a77a4f7034ce7f7b6bb9a4 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:18:19 -0500 Subject: [PATCH 22/46] ready to deploy --- .../LenderCommitmentGroup_Pool_V3.sol | 28 +- .../interfaces/ILenderCommitmentGroup_V3.sol | 2 +- .../lender_commitment_group_v3_beacon.ts | 7 +- .../deploy/pricing/price_adapter_aerodrome.ts | 26 + .../base/UniswapPricingLibrary.json | 28 +- .../base/UniswapPricingLibraryV2.json | 28 +- .../deployments/base/V2Calculations.json | 28 +- .../e1115900f37e3e7c213e9bcaf13e1b45.json | 986 ++++++++++++++++++ 8 files changed, 1070 insertions(+), 63 deletions(-) create mode 100644 packages/contracts/deploy/pricing/price_adapter_aerodrome.ts create mode 100644 packages/contracts/deployments/base/solcInputs/e1115900f37e3e7c213e9bcaf13e1b45.json diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 257224879..8edd12e77 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -112,7 +112,7 @@ contract LenderCommitmentGroup_Pool_V3 is /// @custom:oz-upgrades-unsafe-allow state-variable-immutable address public immutable TELLER_V2; address public immutable SMART_COMMITMENT_FORWARDER; - address public immutable PRICE_ADAPTER; + address public priceAdapter; @@ -271,14 +271,12 @@ contract LenderCommitmentGroup_Pool_V3 is /// @custom:oz-upgrades-unsafe-allow constructor constructor( address _tellerV2, - address _smartCommitmentForwarder, - - address _priceAdapter + address _smartCommitmentForwarder ) OracleProtectedChild(_smartCommitmentForwarder) { TELLER_V2 = _tellerV2; SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder; - PRICE_ADAPTER = _priceAdapter; + } /** @@ -290,6 +288,8 @@ contract LenderCommitmentGroup_Pool_V3 is function initialize( CommitmentGroupConfig calldata _commitmentGroupConfig, + + address _priceAdapter, bytes calldata _priceAdapterRoute @@ -329,11 +329,11 @@ contract LenderCommitmentGroup_Pool_V3 is require( liquidityThresholdPercent <= 10000, "ILTP"); - - + priceAdapter = _priceAdapter ; + //internally this does checks and might revert // we register the price route with the adapter and save it locally - priceRouteHash = IPriceAdapter( PRICE_ADAPTER ).registerPriceRoute( + priceRouteHash = IPriceAdapter( priceAdapter ).registerPriceRoute( _priceAdapterRoute ); @@ -715,17 +715,11 @@ contract LenderCommitmentGroup_Pool_V3 is // principalPerCollateralAmount - uint256 priceRatioQ96 = IPriceAdapter( PRICE_ADAPTER ) + uint256 priceRatioQ96 = IPriceAdapter( priceAdapter ) .getPriceRatioQ96(priceRouteHash); - - /* uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 - ? pairPriceWithTwapFromOracle - : Math.min( - pairPriceWithTwapFromOracle, - maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor - ); */ - + + return getRequiredCollateral( diff --git a/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol b/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol index b45fbef5e..4c3367bd2 100644 --- a/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol +++ b/packages/contracts/contracts/interfaces/ILenderCommitmentGroup_V3.sol @@ -22,7 +22,7 @@ interface ILenderCommitmentGroup_V3 { function initialize( CommitmentGroupConfig calldata _commitmentGroupConfig, - + address _priceAdapterAddress, bytes calldata _priceAdapterRoute ) diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts index a695016f6..3d9f89d5c 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts @@ -27,7 +27,7 @@ const deployFn: DeployFunction = async (hre) => { // const uniswapPricingLibraryV2 = await hre.contracts.get('UniswapPricingLibraryV2') - const priceAdapterAddress = await hre.contracts.get('PriceAdapterAerodrome') + // const priceAdapterAddress = await hre.contracts.get('PriceAdapterAerodrome') const smartCommitmentForwarderAddress = @@ -44,7 +44,7 @@ const deployFn: DeployFunction = async (hre) => { constructorArgs: [ tellerV2Address, smartCommitmentForwarderAddress, - priceAdapterAddress, + // priceAdapterAddress, ], @@ -73,7 +73,8 @@ deployFn.id = 'lender-commitment-group-beacon-v3:deploy' deployFn.tags = ['lender-commitment-group-beacon-v3'] deployFn.dependencies = [ 'teller-v2:deploy', - 'smart-commitment-forwarder:deploy' + 'smart-commitment-forwarder:deploy' , +// 'price-adapter-aerodrome:deploy', ] diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts new file mode 100644 index 000000000..5dfd757f4 --- /dev/null +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -0,0 +1,26 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + + + + const { deployer } = await hre.getNamedAccounts() + const PriceAdapterAerodrome = await hre.deployments.deploy('PriceAdapterAerodrome', { + from: deployer, + }) + + hre.log('Deploying PriceAdapterAerodrome') + + +} + +// tags and deployment +deployFn.id = 'price-adapter-aerodrome:deploy' +deployFn.tags = ['teller-v2', 'price-adapter-aerodrome:deploy'] +deployFn.dependencies = [''] + +deployFn.skip = async (hre) => { + return !hre.network.live || ![ 'base', ].includes(hre.network.name) + } + +export default deployFn \ No newline at end of file diff --git a/packages/contracts/deployments/base/UniswapPricingLibrary.json b/packages/contracts/deployments/base/UniswapPricingLibrary.json index 1e35502ab..c67034562 100644 --- a/packages/contracts/deployments/base/UniswapPricingLibrary.json +++ b/packages/contracts/deployments/base/UniswapPricingLibrary.json @@ -1,5 +1,5 @@ { - "address": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b", + "address": "0xfdC723Aa9874530470DA36cc0791b7DC1201a6ec", "abi": [ { "inputs": [ @@ -94,28 +94,28 @@ "type": "function" } ], - "transactionHash": "0xa7169695a6ecec79c47740bc060e6bf2118d499851940e26d08fe6e0812f91a4", + "transactionHash": "0x5604d96f7941811bc4e20c1fe311e7d2a6b4aa7303b5dcc4275198d609b12e27", "receipt": { "to": null, "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b", - "transactionIndex": 131, - "gasUsed": "905026", + "contractAddress": "0xfdC723Aa9874530470DA36cc0791b7DC1201a6ec", + "transactionIndex": 0, + "gasUsed": "877164", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x20cc84c73ec81e3de2285c4c75222818ff098a50c6ae4a8828da01a47c57a8fb", - "transactionHash": "0xa7169695a6ecec79c47740bc060e6bf2118d499851940e26d08fe6e0812f91a4", + "blockHash": "0xa261ff656f48050061222ba3e4050137164d997bdd2a06d6451417814ba0a1c4", + "transactionHash": "0x5604d96f7941811bc4e20c1fe311e7d2a6b4aa7303b5dcc4275198d609b12e27", "logs": [], - "blockNumber": 24824424, - "cumulativeGasUsed": "24036026", + "blockNumber": 38358495, + "cumulativeGasUsed": "877164", "status": 1, "byzantium": true }, "args": [], - "numDeployments": 1, - "solcInputHash": "8195634c68a34c4192b0d932812f672a", - "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/UniswapPricingLibrary.sol\":\"UniswapPricingLibrary\"},\"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/UniswapPricingLibrary.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 UniswapPricingLibrary \\n{\\n \\n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRouteConfig.pool,\\n _poolRouteConfig.twapInterval\\n );\\n\\n //This is the token 1 per token 0 price\\n uint256 sqrtPrice = FullMath.mulDiv(\\n sqrtPriceX96,\\n STANDARD_EXPANSION_FACTOR,\\n 2**96\\n );\\n\\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\\n\\n uint256 price = _poolRouteConfig.zeroForOne\\n ? sqrtPrice * sqrtPrice\\n : sqrtPriceInverse * sqrtPriceInverse;\\n\\n return price / STANDARD_EXPANSION_FACTOR;\\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\":\"0x89fa90d3bba54e357a693f9e0ea96920edfd60c16f8a6a77a32892f4cafd60f3\",\"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": "0x610f6961003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", - "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", + "numDeployments": 2, + "solcInputHash": "e1115900f37e3e7c213e9bcaf13e1b45", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"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/UniswapPricingLibrary.sol\":\"UniswapPricingLibrary\"},\"evmVersion\":\"shanghai\",\"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/UniswapPricingLibrary.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 UniswapPricingLibrary \\n{\\n \\n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRouteConfig.pool,\\n _poolRouteConfig.twapInterval\\n );\\n\\n //This is the token 1 per token 0 price\\n uint256 sqrtPrice = FullMath.mulDiv(\\n sqrtPriceX96,\\n STANDARD_EXPANSION_FACTOR,\\n 2**96\\n );\\n\\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\\n\\n uint256 price = _poolRouteConfig.zeroForOne\\n ? sqrtPrice * sqrtPrice\\n : sqrtPriceInverse * sqrtPriceInverse;\\n\\n return price / STANDARD_EXPANSION_FACTOR;\\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\":\"0x89fa90d3bba54e357a693f9e0ea96920edfd60c16f8a6a77a32892f4cafd60f3\",\"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": "0x610ee3610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe730000000000000000000000000000000000000000301460806040526004361061003f575f3560e01c80631217931b14610043578063caf0f03314610068575b5f80fd5b610056610051366004610a43565b61007b565b60405190815260200160405180910390f35b610056610076366004610a80565b610114565b5f8061008e835f015184604001516101f7565b90505f6100b1826001600160a01b0316670de0b6b3a7640000600160601b6103c5565b90505f816100c7670de0b6b3a764000080610b35565b6100d19190610b60565b90505f85602001516100ec576100e78280610b35565b6100f6565b6100f68380610b35565b905061010a670de0b6b3a764000082610b60565b9695505050505050565b5f60028251111561016c5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002036101ce575f610198835f8151811061018b5761018b610b73565b602002602001015161007b565b90505f6101b18460018151811061018b5761018b610b73565b90506101c68282670de0b6b3a76400006103c5565b949350505050565b81516001036101f2576101ec825f8151811061018b5761018b610b73565b92915050565b919050565b5f8163ffffffff165f0361027457826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610241573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102659190610b98565b509495506101ec945050505050565b6040805160028082526060820183525f9260208301908036833701905050905061029f836001610c30565b815f815181106102b1576102b1610b73565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102e0576102e0610b73565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd90610323908590600401610c54565b5f60405180830381865afa15801561033d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526103649190810190610d0d565b5090506103bc8460030b825f8151811061038057610380610b73565b60200260200101518360018151811061039b5761039b610b73565b60200260200101516103ad9190610dd1565b6103b79190610dfe565b610536565b95945050505050565b5f80805f19858709858702925082811083820303915050805f036103f9575f84116103ee575f80fd5b50829004905061052f565b808411610404575f80fd5b5f848688098084039381119092039190505f8561042381196001610e3a565b16958690049593849004935f8190030460010190506104428184610b35565b909317925f610452876003610b35565b60021890506104618188610b35565b61046c906002610e4d565b6104769082610b35565b90506104828188610b35565b61048d906002610e4d565b6104979082610b35565b90506104a38188610b35565b6104ae906002610e4d565b6104b89082610b35565b90506104c48188610b35565b6104cf906002610e4d565b6104d99082610b35565b90506104e58188610b35565b6104f0906002610e4d565b6104fa9082610b35565b90506105068188610b35565b610511906002610e4d565b61051b9082610b35565b90506105278186610b35565b955050505050505b9392505050565b5f805f8360020b1261054b578260020b610558565b8260020b61055890610e60565b9050610567620d89e719610e7a565b62ffffff1681111561059f5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610163565b5f816001165f036105b457600160801b6105c6565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610605576080610600826ffff97272373d413259a46990580e213a610b35565b901c90505b600482161561062f57608061062a826ffff2e50f5f656932ef12357cf3c7fdcc610b35565b901c90505b6008821615610659576080610654826fffe5caca7e10e4e61c3624eaa0941cd0610b35565b901c90505b601082161561068357608061067e826fffcb9843d60f6159c9db58835c926644610b35565b901c90505b60208216156106ad5760806106a8826fff973b41fa98c081472e6896dfb254c0610b35565b901c90505b60408216156106d75760806106d2826fff2ea16466c96a3843ec78b326b52861610b35565b901c90505b60808216156107015760806106fc826ffe5dee046a99a2a811c461f1969c3053610b35565b901c90505b61010082161561072c576080610727826ffcbe86c7900a88aedcffc83b479aa3a4610b35565b901c90505b610200821615610757576080610752826ff987a7253ac413176f2b074cf7815e54610b35565b901c90505b61040082161561078257608061077d826ff3392b0822b70005940c7a398e4b70f3610b35565b901c90505b6108008216156107ad5760806107a8826fe7159475a2c29b7443b29c7fa6e889d9610b35565b901c90505b6110008216156107d85760806107d3826fd097f3bdfd2022b8845ad8f792aa5825610b35565b901c90505b6120008216156108035760806107fe826fa9f746462d870fdf8a65dc1f90e061e5610b35565b901c90505b61400082161561082e576080610829826f70d869a156d2a1b890bb3df62baf32f7610b35565b901c90505b618000821615610859576080610854826f31be135f97d08fd981231505542fcfa6610b35565b901c90505b62010000821615610885576080610880826f09aa508b5b7a84e1c677de54f3e99bc9610b35565b901c90505b620200008216156108b05760806108ab826e5d6af8dedb81196699c329225ee604610b35565b901c90505b620400008216156108da5760806108d5826d2216e584f5fa1ea926041bedfe98610b35565b901c90505b620800008216156109025760806108fd826b048a170391f7dc42444e8fa2610b35565b901c90505b5f8460020b131561091b57610918815f19610b60565b90505b61092a64010000000082610e9a565b15610936576001610938565b5f5b6101c69060ff16602083901c610e3a565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561098657610986610949565b604052919050565b6001600160a01b03811681146109a2575f80fd5b50565b80151581146109a2575f80fd5b5f60a082840312156109c2575f80fd5b60405160a0810181811067ffffffffffffffff821117156109e5576109e5610949565b60405290508082356109f68161098e565b81526020830135610a06816109a5565b6020820152604083013563ffffffff81168114610a21575f80fd5b8060408301525060608301356060820152608083013560808201525092915050565b5f60a08284031215610a53575f80fd5b61052f83836109b2565b5f67ffffffffffffffff821115610a7657610a76610949565b5060051b60200190565b5f6020808385031215610a91575f80fd5b823567ffffffffffffffff811115610aa7575f80fd5b8301601f81018513610ab7575f80fd5b8035610aca610ac582610a5d565b61095d565b8082825260208201915060a0602060a08502860101935088841115610aed575f80fd5b6020850194505b83851015610b1557610b0689866109b2565b83529384019391850191610af4565b50979650505050505050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176101ec576101ec610b21565b634e487b7160e01b5f52601260045260245ffd5b5f82610b6e57610b6e610b4c565b500490565b634e487b7160e01b5f52603260045260245ffd5b805161ffff811681146101f2575f80fd5b5f805f805f805f60e0888a031215610bae575f80fd5b8751610bb98161098e565b8097505060208801518060020b8114610bd0575f80fd5b9550610bde60408901610b87565b9450610bec60608901610b87565b9350610bfa60808901610b87565b925060a088015160ff81168114610c0f575f80fd5b60c0890151909250610c20816109a5565b8091505092959891949750929550565b63ffffffff818116838216019080821115610c4d57610c4d610b21565b5092915050565b602080825282518282018190525f9190848201906040850190845b81811015610c9157835163ffffffff1683529284019291840191600101610c6f565b50909695505050505050565b5f82601f830112610cac575f80fd5b81516020610cbc610ac583610a5d565b8083825260208201915060208460051b870101935086841115610cdd575f80fd5b602086015b84811015610d02578051610cf58161098e565b8352918301918301610ce2565b509695505050505050565b5f8060408385031215610d1e575f80fd5b825167ffffffffffffffff80821115610d35575f80fd5b818501915085601f830112610d48575f80fd5b81516020610d58610ac583610a5d565b82815260059290921b84018101918181019089841115610d76575f80fd5b948201945b83861015610da25785518060060b8114610d93575f80fd5b82529482019490820190610d7b565b91880151919650909350505080821115610dba575f80fd5b50610dc785828601610c9d565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156101ec576101ec610b21565b5f8160060b8360060b80610e1457610e14610b4c565b667fffffffffffff1982145f1982141615610e3157610e31610b21565b90059392505050565b808201808211156101ec576101ec610b21565b818103818111156101ec576101ec610b21565b5f600160ff1b8201610e7457610e74610b21565b505f0390565b5f8160020b627fffff198103610e9257610e92610b21565b5f0392915050565b5f82610ea857610ea8610b4c565b50069056fea2646970667358221220a28ead9223c1b9af13974fcc666afda585d1f5c31e098e51388c4e4347f796ae64736f6c63430008180033", + "deployedBytecode": "0x730000000000000000000000000000000000000000301460806040526004361061003f575f3560e01c80631217931b14610043578063caf0f03314610068575b5f80fd5b610056610051366004610a43565b61007b565b60405190815260200160405180910390f35b610056610076366004610a80565b610114565b5f8061008e835f015184604001516101f7565b90505f6100b1826001600160a01b0316670de0b6b3a7640000600160601b6103c5565b90505f816100c7670de0b6b3a764000080610b35565b6100d19190610b60565b90505f85602001516100ec576100e78280610b35565b6100f6565b6100f68380610b35565b905061010a670de0b6b3a764000082610b60565b9695505050505050565b5f60028251111561016c5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002036101ce575f610198835f8151811061018b5761018b610b73565b602002602001015161007b565b90505f6101b18460018151811061018b5761018b610b73565b90506101c68282670de0b6b3a76400006103c5565b949350505050565b81516001036101f2576101ec825f8151811061018b5761018b610b73565b92915050565b919050565b5f8163ffffffff165f0361027457826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610241573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102659190610b98565b509495506101ec945050505050565b6040805160028082526060820183525f9260208301908036833701905050905061029f836001610c30565b815f815181106102b1576102b1610b73565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102e0576102e0610b73565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd90610323908590600401610c54565b5f60405180830381865afa15801561033d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526103649190810190610d0d565b5090506103bc8460030b825f8151811061038057610380610b73565b60200260200101518360018151811061039b5761039b610b73565b60200260200101516103ad9190610dd1565b6103b79190610dfe565b610536565b95945050505050565b5f80805f19858709858702925082811083820303915050805f036103f9575f84116103ee575f80fd5b50829004905061052f565b808411610404575f80fd5b5f848688098084039381119092039190505f8561042381196001610e3a565b16958690049593849004935f8190030460010190506104428184610b35565b909317925f610452876003610b35565b60021890506104618188610b35565b61046c906002610e4d565b6104769082610b35565b90506104828188610b35565b61048d906002610e4d565b6104979082610b35565b90506104a38188610b35565b6104ae906002610e4d565b6104b89082610b35565b90506104c48188610b35565b6104cf906002610e4d565b6104d99082610b35565b90506104e58188610b35565b6104f0906002610e4d565b6104fa9082610b35565b90506105068188610b35565b610511906002610e4d565b61051b9082610b35565b90506105278186610b35565b955050505050505b9392505050565b5f805f8360020b1261054b578260020b610558565b8260020b61055890610e60565b9050610567620d89e719610e7a565b62ffffff1681111561059f5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610163565b5f816001165f036105b457600160801b6105c6565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610605576080610600826ffff97272373d413259a46990580e213a610b35565b901c90505b600482161561062f57608061062a826ffff2e50f5f656932ef12357cf3c7fdcc610b35565b901c90505b6008821615610659576080610654826fffe5caca7e10e4e61c3624eaa0941cd0610b35565b901c90505b601082161561068357608061067e826fffcb9843d60f6159c9db58835c926644610b35565b901c90505b60208216156106ad5760806106a8826fff973b41fa98c081472e6896dfb254c0610b35565b901c90505b60408216156106d75760806106d2826fff2ea16466c96a3843ec78b326b52861610b35565b901c90505b60808216156107015760806106fc826ffe5dee046a99a2a811c461f1969c3053610b35565b901c90505b61010082161561072c576080610727826ffcbe86c7900a88aedcffc83b479aa3a4610b35565b901c90505b610200821615610757576080610752826ff987a7253ac413176f2b074cf7815e54610b35565b901c90505b61040082161561078257608061077d826ff3392b0822b70005940c7a398e4b70f3610b35565b901c90505b6108008216156107ad5760806107a8826fe7159475a2c29b7443b29c7fa6e889d9610b35565b901c90505b6110008216156107d85760806107d3826fd097f3bdfd2022b8845ad8f792aa5825610b35565b901c90505b6120008216156108035760806107fe826fa9f746462d870fdf8a65dc1f90e061e5610b35565b901c90505b61400082161561082e576080610829826f70d869a156d2a1b890bb3df62baf32f7610b35565b901c90505b618000821615610859576080610854826f31be135f97d08fd981231505542fcfa6610b35565b901c90505b62010000821615610885576080610880826f09aa508b5b7a84e1c677de54f3e99bc9610b35565b901c90505b620200008216156108b05760806108ab826e5d6af8dedb81196699c329225ee604610b35565b901c90505b620400008216156108da5760806108d5826d2216e584f5fa1ea926041bedfe98610b35565b901c90505b620800008216156109025760806108fd826b048a170391f7dc42444e8fa2610b35565b901c90505b5f8460020b131561091b57610918815f19610b60565b90505b61092a64010000000082610e9a565b15610936576001610938565b5f5b6101c69060ff16602083901c610e3a565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561098657610986610949565b604052919050565b6001600160a01b03811681146109a2575f80fd5b50565b80151581146109a2575f80fd5b5f60a082840312156109c2575f80fd5b60405160a0810181811067ffffffffffffffff821117156109e5576109e5610949565b60405290508082356109f68161098e565b81526020830135610a06816109a5565b6020820152604083013563ffffffff81168114610a21575f80fd5b8060408301525060608301356060820152608083013560808201525092915050565b5f60a08284031215610a53575f80fd5b61052f83836109b2565b5f67ffffffffffffffff821115610a7657610a76610949565b5060051b60200190565b5f6020808385031215610a91575f80fd5b823567ffffffffffffffff811115610aa7575f80fd5b8301601f81018513610ab7575f80fd5b8035610aca610ac582610a5d565b61095d565b8082825260208201915060a0602060a08502860101935088841115610aed575f80fd5b6020850194505b83851015610b1557610b0689866109b2565b83529384019391850191610af4565b50979650505050505050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176101ec576101ec610b21565b634e487b7160e01b5f52601260045260245ffd5b5f82610b6e57610b6e610b4c565b500490565b634e487b7160e01b5f52603260045260245ffd5b805161ffff811681146101f2575f80fd5b5f805f805f805f60e0888a031215610bae575f80fd5b8751610bb98161098e565b8097505060208801518060020b8114610bd0575f80fd5b9550610bde60408901610b87565b9450610bec60608901610b87565b9350610bfa60808901610b87565b925060a088015160ff81168114610c0f575f80fd5b60c0890151909250610c20816109a5565b8091505092959891949750929550565b63ffffffff818116838216019080821115610c4d57610c4d610b21565b5092915050565b602080825282518282018190525f9190848201906040850190845b81811015610c9157835163ffffffff1683529284019291840191600101610c6f565b50909695505050505050565b5f82601f830112610cac575f80fd5b81516020610cbc610ac583610a5d565b8083825260208201915060208460051b870101935086841115610cdd575f80fd5b602086015b84811015610d02578051610cf58161098e565b8352918301918301610ce2565b509695505050505050565b5f8060408385031215610d1e575f80fd5b825167ffffffffffffffff80821115610d35575f80fd5b818501915085601f830112610d48575f80fd5b81516020610d58610ac583610a5d565b82815260059290921b84018101918181019089841115610d76575f80fd5b948201945b83861015610da25785518060060b8114610d93575f80fd5b82529482019490820190610d7b565b91880151919650909350505080821115610dba575f80fd5b50610dc785828601610c9d565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156101ec576101ec610b21565b5f8160060b8360060b80610e1457610e14610b4c565b667fffffffffffff1982145f1982141615610e3157610e31610b21565b90059392505050565b808201808211156101ec576101ec610b21565b818103818111156101ec576101ec610b21565b5f600160ff1b8201610e7457610e74610b21565b505f0390565b5f8160020b627fffff198103610e9257610e92610b21565b5f0392915050565b5f82610ea857610ea8610b4c565b50069056fea2646970667358221220a28ead9223c1b9af13974fcc666afda585d1f5c31e098e51388c4e4347f796ae64736f6c63430008180033", "devdoc": { "kind": "dev", "methods": {}, diff --git a/packages/contracts/deployments/base/UniswapPricingLibraryV2.json b/packages/contracts/deployments/base/UniswapPricingLibraryV2.json index 4680cbc6b..311dcd71f 100644 --- a/packages/contracts/deployments/base/UniswapPricingLibraryV2.json +++ b/packages/contracts/deployments/base/UniswapPricingLibraryV2.json @@ -1,5 +1,5 @@ { - "address": "0xbD9B31A1a52340813F0191b869C8CC919990613E", + "address": "0xF2F197D71Cd7C247af0d63F0b5c5D8745AA27Cdb", "abi": [ { "inputs": [ @@ -94,28 +94,28 @@ "type": "function" } ], - "transactionHash": "0x5d2e12b90760e8c2b2632345d1eeb9c2710065e5012f0ad1ec09b3c874d9fbee", + "transactionHash": "0xbbb8273d1d87f12c499a8f3868623e9482f9f8c15445b3c9a7949ac424caefc7", "receipt": { "to": null, "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0xbD9B31A1a52340813F0191b869C8CC919990613E", - "transactionIndex": 111, - "gasUsed": "928175", + "contractAddress": "0xF2F197D71Cd7C247af0d63F0b5c5D8745AA27Cdb", + "transactionIndex": 0, + "gasUsed": "900279", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x7d993889b255c1aecc9c964b5f0a33c83a18211ac722ab1d88bc63c548e84d5a", - "transactionHash": "0x5d2e12b90760e8c2b2632345d1eeb9c2710065e5012f0ad1ec09b3c874d9fbee", + "blockHash": "0x0fd5a54db6cac43d35953a40fab239ee4fd2c3797a4c56312350322416a6cf7c", + "transactionHash": "0xbbb8273d1d87f12c499a8f3868623e9482f9f8c15445b3c9a7949ac424caefc7", "logs": [], - "blockNumber": 32042806, - "cumulativeGasUsed": "23745922", + "blockNumber": 38358496, + "cumulativeGasUsed": "900279", "status": 1, "byzantium": true }, "args": [], - "numDeployments": 1, - "solcInputHash": "78e0619e027011a9a52aeb851c216938", - "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/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\"},\"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\\n \\n \\n// Libraries \\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x8d3fc2a832e4d6af64a0bd3a94aa3b86fe2324b95b702d196bc053c4b4e334e1\",\"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": "0x610fd461003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", - "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", + "numDeployments": 2, + "solcInputHash": "e1115900f37e3e7c213e9bcaf13e1b45", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"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\":\"shanghai\",\"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/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\"},\"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\\n \\n \\n// Libraries \\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x8d3fc2a832e4d6af64a0bd3a94aa3b86fe2324b95b702d196bc053c4b4e334e1\",\"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": "0x610f4e610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe730000000000000000000000000000000000000000301460806040526004361061003f575f3560e01c80631217931b14610043578063caf0f03314610068575b5f80fd5b610056610051366004610aae565b61007b565b60405190815260200160405180910390f35b610056610076366004610aeb565b6100b2565b5f8061008e835f0151846040015161018d565b6020840151909150156100aa82670de0b6b3a76400008361035b565b949350505050565b5f60028251111561010a5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600203610164575f610136835f8151811061012957610129610b8c565b602002602001015161007b565b90505f61014f8460018151811061012957610129610b8c565b90506100aa8282670de0b6b3a7640000610432565b815160010361018857610182825f8151811061012957610129610b8c565b92915050565b919050565b5f8163ffffffff165f0361020a57826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101d7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101fb9190610bb1565b50949550610182945050505050565b6040805160028082526060820183525f92602083019080368337019050509050610235836001610c5d565b815f8151811061024757610247610b8c565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061027657610276610b8c565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd906102b9908590600401610c81565b5f60405180830381865afa1580156102d3573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526102fa9190810190610d3a565b5090506103528460030b825f8151811061031657610316610b8c565b60200260200101518360018151811061033157610331610b8c565b60200260200101516103439190610dfe565b61034d9190610e3f565b6105a1565b95945050505050565b5f6001600160801b036001600160a01b038516116103cc575f6103876001600160a01b03861680610e7b565b905082156103ac576103a7600160c01b856001600160801b031683610432565b6103c4565b6103c481856001600160801b0316600160c01b610432565b91505061042b565b5f6103ea6001600160a01b0386168068010000000000000000610432565b9050821561040f5761040a600160801b856001600160801b031683610432565b610427565b61042781856001600160801b0316600160801b610432565b9150505b9392505050565b5f80805f19858709858702925082811083820303915050805f03610466575f841161045b575f80fd5b50829004905061042b565b808411610471575f80fd5b5f848688098084039381119092039190505f8561049081196001610e92565b16958690049593849004935f8190030460010190506104af8184610e7b565b909317925f6104bf876003610e7b565b60021890506104ce8188610e7b565b6104d9906002610ea5565b6104e39082610e7b565b90506104ef8188610e7b565b6104fa906002610ea5565b6105049082610e7b565b90506105108188610e7b565b61051b906002610ea5565b6105259082610e7b565b90506105318188610e7b565b61053c906002610ea5565b6105469082610e7b565b90506105528188610e7b565b61055d906002610ea5565b6105679082610e7b565b90506105738188610e7b565b61057e906002610ea5565b6105889082610e7b565b90506105948186610e7b565b9998505050505050505050565b5f805f8360020b126105b6578260020b6105c3565b8260020b6105c390610eb8565b90506105d2620d89e719610ed2565b62ffffff1681111561060a5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610101565b5f816001165f0361061f57600160801b610631565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561067057608061066b826ffff97272373d413259a46990580e213a610e7b565b901c90505b600482161561069a576080610695826ffff2e50f5f656932ef12357cf3c7fdcc610e7b565b901c90505b60088216156106c45760806106bf826fffe5caca7e10e4e61c3624eaa0941cd0610e7b565b901c90505b60108216156106ee5760806106e9826fffcb9843d60f6159c9db58835c926644610e7b565b901c90505b6020821615610718576080610713826fff973b41fa98c081472e6896dfb254c0610e7b565b901c90505b604082161561074257608061073d826fff2ea16466c96a3843ec78b326b52861610e7b565b901c90505b608082161561076c576080610767826ffe5dee046a99a2a811c461f1969c3053610e7b565b901c90505b610100821615610797576080610792826ffcbe86c7900a88aedcffc83b479aa3a4610e7b565b901c90505b6102008216156107c25760806107bd826ff987a7253ac413176f2b074cf7815e54610e7b565b901c90505b6104008216156107ed5760806107e8826ff3392b0822b70005940c7a398e4b70f3610e7b565b901c90505b610800821615610818576080610813826fe7159475a2c29b7443b29c7fa6e889d9610e7b565b901c90505b61100082161561084357608061083e826fd097f3bdfd2022b8845ad8f792aa5825610e7b565b901c90505b61200082161561086e576080610869826fa9f746462d870fdf8a65dc1f90e061e5610e7b565b901c90505b614000821615610899576080610894826f70d869a156d2a1b890bb3df62baf32f7610e7b565b901c90505b6180008216156108c45760806108bf826f31be135f97d08fd981231505542fcfa6610e7b565b901c90505b620100008216156108f05760806108eb826f09aa508b5b7a84e1c677de54f3e99bc9610e7b565b901c90505b6202000082161561091b576080610916826e5d6af8dedb81196699c329225ee604610e7b565b901c90505b62040000821615610945576080610940826d2216e584f5fa1ea926041bedfe98610e7b565b901c90505b6208000082161561096d576080610968826b048a170391f7dc42444e8fa2610e7b565b901c90505b5f8460020b131561098657610983815f19610ef2565b90505b61099564010000000082610f05565b156109a15760016109a3565b5f5b6100aa9060ff16602083901c610e92565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109f1576109f16109b4565b604052919050565b6001600160a01b0381168114610a0d575f80fd5b50565b8015158114610a0d575f80fd5b5f60a08284031215610a2d575f80fd5b60405160a0810181811067ffffffffffffffff82111715610a5057610a506109b4565b6040529050808235610a61816109f9565b81526020830135610a7181610a10565b6020820152604083013563ffffffff81168114610a8c575f80fd5b8060408301525060608301356060820152608083013560808201525092915050565b5f60a08284031215610abe575f80fd5b61042b8383610a1d565b5f67ffffffffffffffff821115610ae157610ae16109b4565b5060051b60200190565b5f6020808385031215610afc575f80fd5b823567ffffffffffffffff811115610b12575f80fd5b8301601f81018513610b22575f80fd5b8035610b35610b3082610ac8565b6109c8565b8082825260208201915060a0602060a08502860101935088841115610b58575f80fd5b6020850194505b83851015610b8057610b718986610a1d565b83529384019391850191610b5f565b50979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b805161ffff81168114610188575f80fd5b5f805f805f805f60e0888a031215610bc7575f80fd5b8751610bd2816109f9565b8097505060208801518060020b8114610be9575f80fd5b9550610bf760408901610ba0565b9450610c0560608901610ba0565b9350610c1360808901610ba0565b925060a088015160ff81168114610c28575f80fd5b60c0890151909250610c3981610a10565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b63ffffffff818116838216019080821115610c7a57610c7a610c49565b5092915050565b602080825282518282018190525f9190848201906040850190845b81811015610cbe57835163ffffffff1683529284019291840191600101610c9c565b50909695505050505050565b5f82601f830112610cd9575f80fd5b81516020610ce9610b3083610ac8565b8083825260208201915060208460051b870101935086841115610d0a575f80fd5b602086015b84811015610d2f578051610d22816109f9565b8352918301918301610d0f565b509695505050505050565b5f8060408385031215610d4b575f80fd5b825167ffffffffffffffff80821115610d62575f80fd5b818501915085601f830112610d75575f80fd5b81516020610d85610b3083610ac8565b82815260059290921b84018101918181019089841115610da3575f80fd5b948201945b83861015610dcf5785518060060b8114610dc0575f80fd5b82529482019490820190610da8565b91880151919650909350505080821115610de7575f80fd5b50610df485828601610cca565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff8213171561018257610182610c49565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b80610e5557610e55610e2b565b667fffffffffffff1982145f1982141615610e7257610e72610c49565b90059392505050565b808202811582820484141761018257610182610c49565b8082018082111561018257610182610c49565b8181038181111561018257610182610c49565b5f600160ff1b8201610ecc57610ecc610c49565b505f0390565b5f8160020b627fffff198103610eea57610eea610c49565b5f0392915050565b5f82610f0057610f00610e2b565b500490565b5f82610f1357610f13610e2b565b50069056fea264697066735822122094c49a63f22db37e421eac930ca594623732637e5d5cd0ded5579d49255e993464736f6c63430008180033", + "deployedBytecode": "0x730000000000000000000000000000000000000000301460806040526004361061003f575f3560e01c80631217931b14610043578063caf0f03314610068575b5f80fd5b610056610051366004610aae565b61007b565b60405190815260200160405180910390f35b610056610076366004610aeb565b6100b2565b5f8061008e835f0151846040015161018d565b6020840151909150156100aa82670de0b6b3a76400008361035b565b949350505050565b5f60028251111561010a5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600203610164575f610136835f8151811061012957610129610b8c565b602002602001015161007b565b90505f61014f8460018151811061012957610129610b8c565b90506100aa8282670de0b6b3a7640000610432565b815160010361018857610182825f8151811061012957610129610b8c565b92915050565b919050565b5f8163ffffffff165f0361020a57826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101d7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101fb9190610bb1565b50949550610182945050505050565b6040805160028082526060820183525f92602083019080368337019050509050610235836001610c5d565b815f8151811061024757610247610b8c565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061027657610276610b8c565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd906102b9908590600401610c81565b5f60405180830381865afa1580156102d3573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526102fa9190810190610d3a565b5090506103528460030b825f8151811061031657610316610b8c565b60200260200101518360018151811061033157610331610b8c565b60200260200101516103439190610dfe565b61034d9190610e3f565b6105a1565b95945050505050565b5f6001600160801b036001600160a01b038516116103cc575f6103876001600160a01b03861680610e7b565b905082156103ac576103a7600160c01b856001600160801b031683610432565b6103c4565b6103c481856001600160801b0316600160c01b610432565b91505061042b565b5f6103ea6001600160a01b0386168068010000000000000000610432565b9050821561040f5761040a600160801b856001600160801b031683610432565b610427565b61042781856001600160801b0316600160801b610432565b9150505b9392505050565b5f80805f19858709858702925082811083820303915050805f03610466575f841161045b575f80fd5b50829004905061042b565b808411610471575f80fd5b5f848688098084039381119092039190505f8561049081196001610e92565b16958690049593849004935f8190030460010190506104af8184610e7b565b909317925f6104bf876003610e7b565b60021890506104ce8188610e7b565b6104d9906002610ea5565b6104e39082610e7b565b90506104ef8188610e7b565b6104fa906002610ea5565b6105049082610e7b565b90506105108188610e7b565b61051b906002610ea5565b6105259082610e7b565b90506105318188610e7b565b61053c906002610ea5565b6105469082610e7b565b90506105528188610e7b565b61055d906002610ea5565b6105679082610e7b565b90506105738188610e7b565b61057e906002610ea5565b6105889082610e7b565b90506105948186610e7b565b9998505050505050505050565b5f805f8360020b126105b6578260020b6105c3565b8260020b6105c390610eb8565b90506105d2620d89e719610ed2565b62ffffff1681111561060a5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610101565b5f816001165f0361061f57600160801b610631565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561067057608061066b826ffff97272373d413259a46990580e213a610e7b565b901c90505b600482161561069a576080610695826ffff2e50f5f656932ef12357cf3c7fdcc610e7b565b901c90505b60088216156106c45760806106bf826fffe5caca7e10e4e61c3624eaa0941cd0610e7b565b901c90505b60108216156106ee5760806106e9826fffcb9843d60f6159c9db58835c926644610e7b565b901c90505b6020821615610718576080610713826fff973b41fa98c081472e6896dfb254c0610e7b565b901c90505b604082161561074257608061073d826fff2ea16466c96a3843ec78b326b52861610e7b565b901c90505b608082161561076c576080610767826ffe5dee046a99a2a811c461f1969c3053610e7b565b901c90505b610100821615610797576080610792826ffcbe86c7900a88aedcffc83b479aa3a4610e7b565b901c90505b6102008216156107c25760806107bd826ff987a7253ac413176f2b074cf7815e54610e7b565b901c90505b6104008216156107ed5760806107e8826ff3392b0822b70005940c7a398e4b70f3610e7b565b901c90505b610800821615610818576080610813826fe7159475a2c29b7443b29c7fa6e889d9610e7b565b901c90505b61100082161561084357608061083e826fd097f3bdfd2022b8845ad8f792aa5825610e7b565b901c90505b61200082161561086e576080610869826fa9f746462d870fdf8a65dc1f90e061e5610e7b565b901c90505b614000821615610899576080610894826f70d869a156d2a1b890bb3df62baf32f7610e7b565b901c90505b6180008216156108c45760806108bf826f31be135f97d08fd981231505542fcfa6610e7b565b901c90505b620100008216156108f05760806108eb826f09aa508b5b7a84e1c677de54f3e99bc9610e7b565b901c90505b6202000082161561091b576080610916826e5d6af8dedb81196699c329225ee604610e7b565b901c90505b62040000821615610945576080610940826d2216e584f5fa1ea926041bedfe98610e7b565b901c90505b6208000082161561096d576080610968826b048a170391f7dc42444e8fa2610e7b565b901c90505b5f8460020b131561098657610983815f19610ef2565b90505b61099564010000000082610f05565b156109a15760016109a3565b5f5b6100aa9060ff16602083901c610e92565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109f1576109f16109b4565b604052919050565b6001600160a01b0381168114610a0d575f80fd5b50565b8015158114610a0d575f80fd5b5f60a08284031215610a2d575f80fd5b60405160a0810181811067ffffffffffffffff82111715610a5057610a506109b4565b6040529050808235610a61816109f9565b81526020830135610a7181610a10565b6020820152604083013563ffffffff81168114610a8c575f80fd5b8060408301525060608301356060820152608083013560808201525092915050565b5f60a08284031215610abe575f80fd5b61042b8383610a1d565b5f67ffffffffffffffff821115610ae157610ae16109b4565b5060051b60200190565b5f6020808385031215610afc575f80fd5b823567ffffffffffffffff811115610b12575f80fd5b8301601f81018513610b22575f80fd5b8035610b35610b3082610ac8565b6109c8565b8082825260208201915060a0602060a08502860101935088841115610b58575f80fd5b6020850194505b83851015610b8057610b718986610a1d565b83529384019391850191610b5f565b50979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b805161ffff81168114610188575f80fd5b5f805f805f805f60e0888a031215610bc7575f80fd5b8751610bd2816109f9565b8097505060208801518060020b8114610be9575f80fd5b9550610bf760408901610ba0565b9450610c0560608901610ba0565b9350610c1360808901610ba0565b925060a088015160ff81168114610c28575f80fd5b60c0890151909250610c3981610a10565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b63ffffffff818116838216019080821115610c7a57610c7a610c49565b5092915050565b602080825282518282018190525f9190848201906040850190845b81811015610cbe57835163ffffffff1683529284019291840191600101610c9c565b50909695505050505050565b5f82601f830112610cd9575f80fd5b81516020610ce9610b3083610ac8565b8083825260208201915060208460051b870101935086841115610d0a575f80fd5b602086015b84811015610d2f578051610d22816109f9565b8352918301918301610d0f565b509695505050505050565b5f8060408385031215610d4b575f80fd5b825167ffffffffffffffff80821115610d62575f80fd5b818501915085601f830112610d75575f80fd5b81516020610d85610b3083610ac8565b82815260059290921b84018101918181019089841115610da3575f80fd5b948201945b83861015610dcf5785518060060b8114610dc0575f80fd5b82529482019490820190610da8565b91880151919650909350505080821115610de7575f80fd5b50610df485828601610cca565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff8213171561018257610182610c49565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b80610e5557610e55610e2b565b667fffffffffffff1982145f1982141615610e7257610e72610c49565b90059392505050565b808202811582820484141761018257610182610c49565b8082018082111561018257610182610c49565b8181038181111561018257610182610c49565b5f600160ff1b8201610ecc57610ecc610c49565b505f0390565b5f8160020b627fffff198103610eea57610eea610c49565b5f0392915050565b5f82610f0057610f00610e2b565b500490565b5f82610f1357610f13610e2b565b50069056fea264697066735822122094c49a63f22db37e421eac930ca594623732637e5d5cd0ded5579d49255e993464736f6c63430008180033", "devdoc": { "kind": "dev", "methods": {}, diff --git a/packages/contracts/deployments/base/V2Calculations.json b/packages/contracts/deployments/base/V2Calculations.json index 2cdc4453a..3a73266a8 100644 --- a/packages/contracts/deployments/base/V2Calculations.json +++ b/packages/contracts/deployments/base/V2Calculations.json @@ -1,5 +1,5 @@ { - "address": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", + "address": "0xF579ba9Ce33E392134Fd4a1A9D7D9d792eAF0B2b", "abi": [ { "inputs": [ @@ -85,28 +85,28 @@ "type": "function" } ], - "transactionHash": "0x5f741cdf3912c24a782fd8537caf5d45916d27239d05b0c90c8defb8d90cd688", + "transactionHash": "0x49221754b58966d5018310c5f40a29667203d1be5dfbd3346684d6a6b49eec90", "receipt": { "to": null, "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", - "transactionIndex": 124, - "gasUsed": "1135180", + "contractAddress": "0xF579ba9Ce33E392134Fd4a1A9D7D9d792eAF0B2b", + "transactionIndex": 0, + "gasUsed": "1074708", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0xe277899b75cad620db15c3e47b00539f239345d41919c67ff1a40eaed14d4933", - "transactionHash": "0x5f741cdf3912c24a782fd8537caf5d45916d27239d05b0c90c8defb8d90cd688", + "blockHash": "0x6ed07882fe6265fdf6470d823f47d2a97d7a4423315cb421fb5afabfe3a07a1b", + "transactionHash": "0x49221754b58966d5018310c5f40a29667203d1be5dfbd3346684d6a6b49eec90", "logs": [], - "blockNumber": 24824409, - "cumulativeGasUsed": "25265059", + "blockNumber": 38358494, + "cumulativeGasUsed": "1074708", "status": 1, "byzantium": true }, "args": [], - "numDeployments": 3, - "solcInputHash": "8195634c68a34c4192b0d932812f672a", - "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"_acceptedTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_loanDuration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_lastRepaidTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_bidPaymentCycleType\",\"type\":\"PaymentCycleType\"}],\"name\":\"calculateNextDueDate\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"dueDate_\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"enum PaymentType\",\"name\":\"_type\",\"type\":\"PaymentType\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_cycleType\",\"type\":\"PaymentCycleType\"},{\"internalType\":\"uint256\",\"name\":\"_principal\",\"type\":\"uint256\"},{\"internalType\":\"uint32\",\"name\":\"_duration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint16\",\"name\":\"_apr\",\"type\":\"uint16\"}],\"name\":\"calculatePaymentCycleAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"params\":{\"_bid\":\"The loan bid struct to get the owed amount for.\",\"_paymentCycleType\":\"The payment cycle type of the loan (Seconds or Monthly).\",\"_timestamp\":\"The timestamp at which to get the owed amount at.\"}},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"params\":{\"_apr\":\"The annual percentage rate of the loan.\",\"_cycleType\":\"The cycle type set for the loan. (Seconds or Monthly)\",\"_duration\":\"The length of the loan.\",\"_paymentCycle\":\"The length of the loan's payment cycle.\",\"_principal\":\"The starting amount that is owed on the loan.\",\"_type\":\"The payment type of the loan.\"}}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"notice\":\"Calculates the amount owed for a loan.\"},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"notice\":\"Calculates the amount owed for a loan for the next payment cycle.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/V2Calculations.sol\":\"V2Calculations\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@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\",\"keccak256\":\"0x2c0b89cef83f353c6f9488c013d8a5968587ffdd6dfc26aad53774214b97e229\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc6cef87559d0aeffdf0a99803de655938a7779ec0a3cd5d4383483ad85565a09\",\"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\"},\"@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\",\"keccak256\":\"0x52a8cfb0f5239d11b457dcdd1b326992ef672714ca8da71a157255bddd13f3ad\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x0f633a0223d9a1dcccfcf38a64c9de0874dfcbfac0c6941ccf074d63a2ce0e1e\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc3ff3f5c4584e1d9a483ad7ced51ab64523201f4e3d3c65293e4ca8aeb77a961\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x30aabe18188500137c312a4645ae5030e6edbb73ca3a04141b18f4f9a65aec62\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x58734812c9549a2d53d86ac6349b2fba615460732145e863ef9d0c8dc3712d08\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x7d80ce49d143f2f509e1992ed41200e07376bea48950e3674db71a343882f2c8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xceb1ea2ef4c6e2ad7986db84de49c959e8d59844563d27daca5b8d78b732a8f7\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2a17561a47cb3517f2820d68d9bbcd86dcd21c59cad7208581004ecd91d5478a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8d6e50fd460912231e53135b4459aa2f6f16007ae8deb32bc2cee1e88311a8d8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xc5b554eea7e17e47acc632cab40894bac2d2699864fdccc61e08fa8f546c0437\"},\"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\",\"keccak256\":\"0xf194df8ea9946a5bb3300223629b7e4959c1f20bacba27b3dc5f6dd2a160147a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x78009ffb3737ab7615a1e38a26635d6c06b65b7b7959af46d6ef840d220e70cf\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8452535763bfb5c529a0089b8b669d77cc4e1e333b526b89b5d42ab491fb4312\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2781319be7a96f56966c601c061849fa94dbf9af5ad80a20c40b879a8d03f14a\",\"license\":\"MIT\"}},\"version\":1}", - "bytecode": "0x61139261003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", - "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", + "numDeployments": 4, + "solcInputHash": "e1115900f37e3e7c213e9bcaf13e1b45", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"_acceptedTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_loanDuration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_lastRepaidTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_bidPaymentCycleType\",\"type\":\"PaymentCycleType\"}],\"name\":\"calculateNextDueDate\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"dueDate_\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"enum PaymentType\",\"name\":\"_type\",\"type\":\"PaymentType\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_cycleType\",\"type\":\"PaymentCycleType\"},{\"internalType\":\"uint256\",\"name\":\"_principal\",\"type\":\"uint256\"},{\"internalType\":\"uint32\",\"name\":\"_duration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint16\",\"name\":\"_apr\",\"type\":\"uint16\"}],\"name\":\"calculatePaymentCycleAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"params\":{\"_bid\":\"The loan bid struct to get the owed amount for.\",\"_paymentCycleType\":\"The payment cycle type of the loan (Seconds or Monthly).\",\"_timestamp\":\"The timestamp at which to get the owed amount at.\"}},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"params\":{\"_apr\":\"The annual percentage rate of the loan.\",\"_cycleType\":\"The cycle type set for the loan. (Seconds or Monthly)\",\"_duration\":\"The length of the loan.\",\"_paymentCycle\":\"The length of the loan's payment cycle.\",\"_principal\":\"The starting amount that is owed on the loan.\",\"_type\":\"The payment type of the loan.\"}}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"notice\":\"Calculates the amount owed for a loan.\"},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"notice\":\"Calculates the amount owed for a loan for the next payment cycle.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/V2Calculations.sol\":\"V2Calculations\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@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\",\"keccak256\":\"0x2c0b89cef83f353c6f9488c013d8a5968587ffdd6dfc26aad53774214b97e229\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc6cef87559d0aeffdf0a99803de655938a7779ec0a3cd5d4383483ad85565a09\",\"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\"},\"@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\",\"keccak256\":\"0x52a8cfb0f5239d11b457dcdd1b326992ef672714ca8da71a157255bddd13f3ad\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x0f633a0223d9a1dcccfcf38a64c9de0874dfcbfac0c6941ccf074d63a2ce0e1e\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc3ff3f5c4584e1d9a483ad7ced51ab64523201f4e3d3c65293e4ca8aeb77a961\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x30aabe18188500137c312a4645ae5030e6edbb73ca3a04141b18f4f9a65aec62\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x58734812c9549a2d53d86ac6349b2fba615460732145e863ef9d0c8dc3712d08\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x7d80ce49d143f2f509e1992ed41200e07376bea48950e3674db71a343882f2c8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xceb1ea2ef4c6e2ad7986db84de49c959e8d59844563d27daca5b8d78b732a8f7\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2a17561a47cb3517f2820d68d9bbcd86dcd21c59cad7208581004ecd91d5478a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8d6e50fd460912231e53135b4459aa2f6f16007ae8deb32bc2cee1e88311a8d8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xc5b554eea7e17e47acc632cab40894bac2d2699864fdccc61e08fa8f546c0437\"},\"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\",\"keccak256\":\"0xf194df8ea9946a5bb3300223629b7e4959c1f20bacba27b3dc5f6dd2a160147a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x78009ffb3737ab7615a1e38a26635d6c06b65b7b7959af46d6ef840d220e70cf\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8452535763bfb5c529a0089b8b669d77cc4e1e333b526b89b5d42ab491fb4312\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2781319be7a96f56966c601c061849fa94dbf9af5ad80a20c40b879a8d03f14a\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x611274610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610054575f3560e01c80628945b5146100585780630dcf16581461007e5780635ab17296146100a6578063e4de10d3146100d4575b5f80fd5b61006b610066366004610e21565b6100e7565b6040519081526020015b60405180910390f35b61009161008c366004610e98565b610183565b60405163ffffffff9091168152602001610075565b6100b96100b4366004610efd565b6102b1565b60408051938452602084019290925290820152606001610075565b6100b96100e2366004610f4b565b610493565b5f8060018760018111156100fd576100fd610f90565b1461010c576301e13380610112565b6301da9c005b63ffffffff169050600188600181111561012e5761012e610f90565b036101685761016061014d63ffffffff808716908490600a906104c116565b600a61015989876104f8565b9190610512565b915050610179565b6101758686868685610526565b9150505b9695505050505050565b5f600182600181111561019857610198610f90565b03610212575f6101b48763ffffffff168563ffffffff16610657565b90506101c58763ffffffff166106da565b6101d48563ffffffff166106da565b11156101ec576101e5600282610fb8565b90506101fa565b6101f7600182610fb8565b90505b61020a8763ffffffff16826106f3565b915050610282565b5f82600181111561022557610225610f90565b03610282576102348587610fcb565b90505f6102418785610fef565b905063ffffffff811615610280575f6102668263ffffffff168863ffffffff166107c2565b9050610272878261100c565b61027c9084610fcb565b9250505b505b5f61028d8588610fcb565b90508063ffffffff168263ffffffff1611156102a7578091505b5095945050505050565b600785015460068601545f91829182916102ca91611034565b92505f6102d78888611034565b90505f60018760018111156102ee576102ee610f90565b146102fd576301e13380610303565b6301da9c005b600b8b015463ffffffff91821692505f9161033191889164010000000090910461ffff169060029061051216565b90508161033e8483611047565b6103489190611072565b60098c01549094505f925082915061036e908890600160601b900463ffffffff16611085565b63ffffffff169050805f03610386575063ffffffff86165b60098b01545f906103ae9063ffffffff600160601b8204811691640100000000900416610fb8565b90505f6103bb8383611034565b9050808b11806103d85750600a8d01546103d5878a610fb8565b11155b9350600192506103e6915050565b600c8b0154610100900460ff16600181111561040457610404610f90565b03610418578015610413578493505b610486565b5f6104548763ffffffff16848d600a015f01546104359190611047565b61043f9190611072565b600a8d015461044f908790610fb8565b6107f7565b90505f82610462578161046c565b61046c8588610fb8565b905061048161047b8683611034565b886107f7565b955050505b5050955095509592505050565b5f805f6104b1876104a38961080c565b63ffffffff168888886102b1565b9250925092509450945094915050565b5f825f036104d057505f6104f1565b826104da83610852565b6104e49086611047565b6104ee9190611072565b90505b9392505050565b5f610509838361ffff166002610512565b90505b92915050565b5f61051c82610852565b6104e48486611047565b5f8363ffffffff168563ffffffff1610156105935760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b8261ffff165f036105be576105b7868563ffffffff168763ffffffff166001610869565b905061064e565b5f6105d58663ffffffff168663ffffffff166107c2565b9050670de0b6b3a76400005f610604856105fe63ffffffff8a166105f88a6108b8565b906108db565b9061090e565b90505f61061b846106158486610fb8565b9061093d565b90505f61062c826105f88d866108db565b90505f6106398584611034565b9050610645828261090e565b96505050505050505b95945050505050565b5f81831115610664575f80fd5b5f8061067b6106766201518087611072565b610954565b5090925090505f806106936106766201518088611072565b509092509050826106a585600c611047565b826106b185600c611047565b6106bb9190610fb8565b6106c59190611034565b6106cf9190611034565b979650505050505050565b5f6106eb6106766201518084611072565b949350505050565b5f8080806107076106766201518088611072565b919450925090506107188583610fb8565b9150600c610727600184611034565b6107319190611072565b61073b9084610fb8565b9250600c61074a600184611034565b61075491906110a7565b61075f906001610fb8565b91505f61076c8484610ac3565b90508082111561077a578091505b61078762015180886110a7565b62015180610796868686610b48565b6107a09190611047565b6107aa9190610fb8565b9450868510156107b8575f80fd5b5050505092915050565b5f82156107ef57816107d5600185611034565b6107df9190611072565b6107ea906001610fb8565b610509565b505f92915050565b5f8183106108055781610509565b5090919050565b60098101545f90600160401b900463ffffffff161561083c576009820154600160401b900463ffffffff1661050c565b5060090154640100000000900463ffffffff1690565b5f61085e82600a61119a565b61050c906064611047565b5f80610876868686610c82565b9050600183600281111561088c5761088c610f90565b1480156108a857505f84806108a3576108a361105e565b868809115b1561064e57610179600182610fb8565b5f61050c6127106108d561ffff8516670de0b6b3a7640000610d2b565b90610d36565b5f610509670de0b6b3a76400006108d56108f58686610d2b565b6109086002670de0b6b3a7640000611072565b90610d41565b5f8061091b600284611072565b90506106eb836108d561093687670de0b6b3a7640000610d2b565b8490610d41565b5f6105098383670de0b6b3a76400006108db610d4c565b5f8080838162253d8c61096a8362010bd96111a5565b61097491906111a5565b90505f62023ab16109868360046111c4565b61099091906111f3565b905060046109a18262023ab16111c4565b6109ac9060036111a5565b6109b691906111f3565b6109c0908361121f565b91505f62164b096109d28460016111a5565b6109de90610fa06111c4565b6109e891906111f3565b905060046109f8826105b56111c4565b610a0291906111f3565b610a0c908461121f565b610a1790601f6111a5565b92505f61098f610a288560506111c4565b610a3291906111f3565b90505f6050610a438361098f6111c4565b610a4d91906111f3565b610a57908661121f565b9050610a64600b836111f3565b9450610a7185600c6111c4565b610a7c8360026111a5565b610a86919061121f565b91508483610a9560318761121f565b610aa09060646111c4565b610aaa91906111a5565b610ab491906111a5565b9a919950975095505050505050565b5f8160011480610ad35750816003145b80610ade5750816005145b80610ae95750816007145b80610af45750816008145b80610aff575081600a145b80610b0a575081600c145b15610b175750601f61050c565b81600214610b275750601e61050c565b610b3083610dbf565b610b3b57601c610b3e565b601d5b60ff169392505050565b5f6107b2841015610b57575f80fd5b8383835f62253d8c60046064600c610b70600e8861121f565b610b7a91906111f3565b610b86886113246111a5565b610b9091906111a5565b610b9a91906111f3565b610ba59060036111c4565b610baf91906111f3565b600c80610bbd600e8861121f565b610bc791906111f3565b610bd290600c6111c4565b610bdd60028861121f565b610be7919061121f565b610bf39061016f6111c4565b610bfd91906111f3565b6004600c610c0c600e8961121f565b610c1691906111f3565b610c22896112c06111a5565b610c2c91906111a5565b610c38906105b56111c4565b610c4291906111f3565b610c4e617d4b8761121f565b610c5891906111a5565b610c6291906111a5565b610c6c919061121f565b610c76919061121f565b98975050505050505050565b5f80805f19858709858702925082811083820303915050805f03610cb957838281610caf57610caf61105e565b04925050506104f1565b808411610cc4575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b5f6105098284611047565b5f6105098284611072565b5f6105098284610fb8565b5f610d586002856110a7565b5f03610d645782610d66565b845b9050610d73600285611072565b93505b83156106eb57610d8a85868463ffffffff16565b9450610d976002856110a7565b15610dad57610daa81868463ffffffff16565b90505b610db8600285611072565b9350610d76565b5f610dcb6004836110a7565b158015610de15750610dde6064836110a7565b15155b8061050c5750610df3610190836110a7565b1592915050565b60028110610e06575f80fd5b50565b803563ffffffff81168114610e1c575f80fd5b919050565b5f805f805f8060c08789031215610e36575f80fd5b8635610e4181610dfa565b95506020870135610e5181610dfa565b945060408701359350610e6660608801610e09565b9250610e7460808801610e09565b915060a087013561ffff81168114610e8a575f80fd5b809150509295509295509295565b5f805f805f60a08688031215610eac575f80fd5b610eb586610e09565b9450610ec360208701610e09565b9350610ed160408701610e09565b9250610edf60608701610e09565b91506080860135610eef81610dfa565b809150509295509295909350565b5f805f805f60a08688031215610f11575f80fd5b8535945060208601359350604086013592506060860135610f3181610dfa565b9150610f3f60808701610e09565b90509295509295909350565b5f805f8060808587031215610f5e575f80fd5b84359350602085013592506040850135610f7781610dfa565b9150610f8560608601610e09565b905092959194509250565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082018082111561050c5761050c610fa4565b63ffffffff818116838216019080821115610fe857610fe8610fa4565b5092915050565b63ffffffff828116828216039080821115610fe857610fe8610fa4565b63ffffffff81811683821602808216919082811461102c5761102c610fa4565b505092915050565b8181038181111561050c5761050c610fa4565b808202811582820484141761050c5761050c610fa4565b634e487b7160e01b5f52601260045260245ffd5b5f826110805761108061105e565b500490565b5f63ffffffff8084168061109b5761109b61105e565b92169190910692915050565b5f826110b5576110b561105e565b500690565b600181815b808511156110f457815f19048211156110da576110da610fa4565b808516156110e757918102915b93841c93908002906110bf565b509250929050565b5f8261110a5750600161050c565b8161111657505f61050c565b816001811461112c576002811461113657611152565b600191505061050c565b60ff84111561114757611147610fa4565b50506001821b61050c565b5060208310610133831016604e8410600b8410161715611175575081810a61050c565b61117f83836110ba565b805f190482111561119257611192610fa4565b029392505050565b5f61050983836110fc565b8082018281125f83128015821682158216171561102c5761102c610fa4565b8082025f8212600160ff1b841416156111df576111df610fa4565b818105831482151761050c5761050c610fa4565b5f826112015761120161105e565b600160ff1b82145f198414161561121a5761121a610fa4565b500590565b8181035f831280158383131683831282161715610fe857610fe8610fa456fea2646970667358221220387e78093bea8461f17d728891fb7826e39186875cab06777fcec9a094aa746964736f6c63430008180033", + "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610054575f3560e01c80628945b5146100585780630dcf16581461007e5780635ab17296146100a6578063e4de10d3146100d4575b5f80fd5b61006b610066366004610e21565b6100e7565b6040519081526020015b60405180910390f35b61009161008c366004610e98565b610183565b60405163ffffffff9091168152602001610075565b6100b96100b4366004610efd565b6102b1565b60408051938452602084019290925290820152606001610075565b6100b96100e2366004610f4b565b610493565b5f8060018760018111156100fd576100fd610f90565b1461010c576301e13380610112565b6301da9c005b63ffffffff169050600188600181111561012e5761012e610f90565b036101685761016061014d63ffffffff808716908490600a906104c116565b600a61015989876104f8565b9190610512565b915050610179565b6101758686868685610526565b9150505b9695505050505050565b5f600182600181111561019857610198610f90565b03610212575f6101b48763ffffffff168563ffffffff16610657565b90506101c58763ffffffff166106da565b6101d48563ffffffff166106da565b11156101ec576101e5600282610fb8565b90506101fa565b6101f7600182610fb8565b90505b61020a8763ffffffff16826106f3565b915050610282565b5f82600181111561022557610225610f90565b03610282576102348587610fcb565b90505f6102418785610fef565b905063ffffffff811615610280575f6102668263ffffffff168863ffffffff166107c2565b9050610272878261100c565b61027c9084610fcb565b9250505b505b5f61028d8588610fcb565b90508063ffffffff168263ffffffff1611156102a7578091505b5095945050505050565b600785015460068601545f91829182916102ca91611034565b92505f6102d78888611034565b90505f60018760018111156102ee576102ee610f90565b146102fd576301e13380610303565b6301da9c005b600b8b015463ffffffff91821692505f9161033191889164010000000090910461ffff169060029061051216565b90508161033e8483611047565b6103489190611072565b60098c01549094505f925082915061036e908890600160601b900463ffffffff16611085565b63ffffffff169050805f03610386575063ffffffff86165b60098b01545f906103ae9063ffffffff600160601b8204811691640100000000900416610fb8565b90505f6103bb8383611034565b9050808b11806103d85750600a8d01546103d5878a610fb8565b11155b9350600192506103e6915050565b600c8b0154610100900460ff16600181111561040457610404610f90565b03610418578015610413578493505b610486565b5f6104548763ffffffff16848d600a015f01546104359190611047565b61043f9190611072565b600a8d015461044f908790610fb8565b6107f7565b90505f82610462578161046c565b61046c8588610fb8565b905061048161047b8683611034565b886107f7565b955050505b5050955095509592505050565b5f805f6104b1876104a38961080c565b63ffffffff168888886102b1565b9250925092509450945094915050565b5f825f036104d057505f6104f1565b826104da83610852565b6104e49086611047565b6104ee9190611072565b90505b9392505050565b5f610509838361ffff166002610512565b90505b92915050565b5f61051c82610852565b6104e48486611047565b5f8363ffffffff168563ffffffff1610156105935760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b8261ffff165f036105be576105b7868563ffffffff168763ffffffff166001610869565b905061064e565b5f6105d58663ffffffff168663ffffffff166107c2565b9050670de0b6b3a76400005f610604856105fe63ffffffff8a166105f88a6108b8565b906108db565b9061090e565b90505f61061b846106158486610fb8565b9061093d565b90505f61062c826105f88d866108db565b90505f6106398584611034565b9050610645828261090e565b96505050505050505b95945050505050565b5f81831115610664575f80fd5b5f8061067b6106766201518087611072565b610954565b5090925090505f806106936106766201518088611072565b509092509050826106a585600c611047565b826106b185600c611047565b6106bb9190610fb8565b6106c59190611034565b6106cf9190611034565b979650505050505050565b5f6106eb6106766201518084611072565b949350505050565b5f8080806107076106766201518088611072565b919450925090506107188583610fb8565b9150600c610727600184611034565b6107319190611072565b61073b9084610fb8565b9250600c61074a600184611034565b61075491906110a7565b61075f906001610fb8565b91505f61076c8484610ac3565b90508082111561077a578091505b61078762015180886110a7565b62015180610796868686610b48565b6107a09190611047565b6107aa9190610fb8565b9450868510156107b8575f80fd5b5050505092915050565b5f82156107ef57816107d5600185611034565b6107df9190611072565b6107ea906001610fb8565b610509565b505f92915050565b5f8183106108055781610509565b5090919050565b60098101545f90600160401b900463ffffffff161561083c576009820154600160401b900463ffffffff1661050c565b5060090154640100000000900463ffffffff1690565b5f61085e82600a61119a565b61050c906064611047565b5f80610876868686610c82565b9050600183600281111561088c5761088c610f90565b1480156108a857505f84806108a3576108a361105e565b868809115b1561064e57610179600182610fb8565b5f61050c6127106108d561ffff8516670de0b6b3a7640000610d2b565b90610d36565b5f610509670de0b6b3a76400006108d56108f58686610d2b565b6109086002670de0b6b3a7640000611072565b90610d41565b5f8061091b600284611072565b90506106eb836108d561093687670de0b6b3a7640000610d2b565b8490610d41565b5f6105098383670de0b6b3a76400006108db610d4c565b5f8080838162253d8c61096a8362010bd96111a5565b61097491906111a5565b90505f62023ab16109868360046111c4565b61099091906111f3565b905060046109a18262023ab16111c4565b6109ac9060036111a5565b6109b691906111f3565b6109c0908361121f565b91505f62164b096109d28460016111a5565b6109de90610fa06111c4565b6109e891906111f3565b905060046109f8826105b56111c4565b610a0291906111f3565b610a0c908461121f565b610a1790601f6111a5565b92505f61098f610a288560506111c4565b610a3291906111f3565b90505f6050610a438361098f6111c4565b610a4d91906111f3565b610a57908661121f565b9050610a64600b836111f3565b9450610a7185600c6111c4565b610a7c8360026111a5565b610a86919061121f565b91508483610a9560318761121f565b610aa09060646111c4565b610aaa91906111a5565b610ab491906111a5565b9a919950975095505050505050565b5f8160011480610ad35750816003145b80610ade5750816005145b80610ae95750816007145b80610af45750816008145b80610aff575081600a145b80610b0a575081600c145b15610b175750601f61050c565b81600214610b275750601e61050c565b610b3083610dbf565b610b3b57601c610b3e565b601d5b60ff169392505050565b5f6107b2841015610b57575f80fd5b8383835f62253d8c60046064600c610b70600e8861121f565b610b7a91906111f3565b610b86886113246111a5565b610b9091906111a5565b610b9a91906111f3565b610ba59060036111c4565b610baf91906111f3565b600c80610bbd600e8861121f565b610bc791906111f3565b610bd290600c6111c4565b610bdd60028861121f565b610be7919061121f565b610bf39061016f6111c4565b610bfd91906111f3565b6004600c610c0c600e8961121f565b610c1691906111f3565b610c22896112c06111a5565b610c2c91906111a5565b610c38906105b56111c4565b610c4291906111f3565b610c4e617d4b8761121f565b610c5891906111a5565b610c6291906111a5565b610c6c919061121f565b610c76919061121f565b98975050505050505050565b5f80805f19858709858702925082811083820303915050805f03610cb957838281610caf57610caf61105e565b04925050506104f1565b808411610cc4575f80fd5b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b5f6105098284611047565b5f6105098284611072565b5f6105098284610fb8565b5f610d586002856110a7565b5f03610d645782610d66565b845b9050610d73600285611072565b93505b83156106eb57610d8a85868463ffffffff16565b9450610d976002856110a7565b15610dad57610daa81868463ffffffff16565b90505b610db8600285611072565b9350610d76565b5f610dcb6004836110a7565b158015610de15750610dde6064836110a7565b15155b8061050c5750610df3610190836110a7565b1592915050565b60028110610e06575f80fd5b50565b803563ffffffff81168114610e1c575f80fd5b919050565b5f805f805f8060c08789031215610e36575f80fd5b8635610e4181610dfa565b95506020870135610e5181610dfa565b945060408701359350610e6660608801610e09565b9250610e7460808801610e09565b915060a087013561ffff81168114610e8a575f80fd5b809150509295509295509295565b5f805f805f60a08688031215610eac575f80fd5b610eb586610e09565b9450610ec360208701610e09565b9350610ed160408701610e09565b9250610edf60608701610e09565b91506080860135610eef81610dfa565b809150509295509295909350565b5f805f805f60a08688031215610f11575f80fd5b8535945060208601359350604086013592506060860135610f3181610dfa565b9150610f3f60808701610e09565b90509295509295909350565b5f805f8060808587031215610f5e575f80fd5b84359350602085013592506040850135610f7781610dfa565b9150610f8560608601610e09565b905092959194509250565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082018082111561050c5761050c610fa4565b63ffffffff818116838216019080821115610fe857610fe8610fa4565b5092915050565b63ffffffff828116828216039080821115610fe857610fe8610fa4565b63ffffffff81811683821602808216919082811461102c5761102c610fa4565b505092915050565b8181038181111561050c5761050c610fa4565b808202811582820484141761050c5761050c610fa4565b634e487b7160e01b5f52601260045260245ffd5b5f826110805761108061105e565b500490565b5f63ffffffff8084168061109b5761109b61105e565b92169190910692915050565b5f826110b5576110b561105e565b500690565b600181815b808511156110f457815f19048211156110da576110da610fa4565b808516156110e757918102915b93841c93908002906110bf565b509250929050565b5f8261110a5750600161050c565b8161111657505f61050c565b816001811461112c576002811461113657611152565b600191505061050c565b60ff84111561114757611147610fa4565b50506001821b61050c565b5060208310610133831016604e8410600b8410161715611175575081810a61050c565b61117f83836110ba565b805f190482111561119257611192610fa4565b029392505050565b5f61050983836110fc565b8082018281125f83128015821682158216171561102c5761102c610fa4565b8082025f8212600160ff1b841416156111df576111df610fa4565b818105831482151761050c5761050c610fa4565b5f826112015761120161105e565b600160ff1b82145f198414161561121a5761121a610fa4565b500590565b8181035f831280158383131683831282161715610fe857610fe8610fa456fea2646970667358221220387e78093bea8461f17d728891fb7826e39186875cab06777fcec9a094aa746964736f6c63430008180033", "devdoc": { "kind": "dev", "methods": { diff --git a/packages/contracts/deployments/base/solcInputs/e1115900f37e3e7c213e9bcaf13e1b45.json b/packages/contracts/deployments/base/solcInputs/e1115900f37e3e7c213e9bcaf13e1b45.json new file mode 100644 index 000000000..ef6af4676 --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/e1115900f37e3e7c213e9bcaf13e1b45.json @@ -0,0 +1,986 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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" + }, + "@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns an account's balance in the token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n FUNCTIONS\n //////////////////////////////////////////////////////////////*/\n\n /// @notice Owner balance of an id.\n /// @param owner The address of the owner.\n /// @param id The id of the token.\n /// @return amount The balance of the token.\n function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n /// @notice Spender allowance of an id.\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @return amount The allowance of the token.\n function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n /// @notice Checks if a spender is approved by an owner as an operator\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @return approved The approval status.\n function isOperator(address owner, address spender) external view returns (bool approved);\n\n /// @notice Transfers an amount of an id from the caller to a receiver.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Transfers an amount of an id from a sender to a receiver.\n /// @param sender The address of the sender.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Approves an amount of an id to a spender.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always\n function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Sets or removes an operator for the caller.\n /// @param operator The address of the operator.\n /// @param approved The approval status.\n /// @return bool True, always\n function setOperator(address operator, bool approved) external returns (bool);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExtsload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n /// @notice Called by external contracts to access granular pool state\n /// @param slot Key of slot to sload\n /// @return value The value of the slot as bytes32\n function extsload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access granular pool state\n /// @param startSlot Key of slot to start sloading from\n /// @param nSlots Number of slots to load into return value\n /// @return values List of loaded values.\n function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n /// @notice Called by external contracts to access sparse pool state\n /// @param slots List of slots to SLOAD from.\n /// @return values List of loaded values.\n function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExttload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n /// @notice Called by external contracts to access transient storage of the contract\n /// @param slot Key of slot to tload\n /// @return value The value of the slot as bytes32\n function exttload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access sparse transient pool state\n /// @param slots List of slots to tload\n /// @return values List of loaded values\n function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IHooks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n /// @notice The hook called before the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @return bytes4 The function selector for the hook\n function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n /// @notice The hook called after the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @param tick The current tick after the state of a pool is initialized\n /// @return bytes4 The function selector for the hook\n function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n external\n returns (bytes4);\n\n /// @notice The hook called before liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n external\n returns (bytes4, BeforeSwapDelta, uint24);\n\n /// @notice The hook called after a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterSwap(\n address sender,\n PoolKey calldata key,\n SwapParams calldata params,\n BalanceDelta delta,\n bytes calldata hookData\n ) external returns (bytes4, int128);\n\n /// @notice The hook called before donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function afterDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IPoolManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n /// @notice Thrown when a currency is not netted out after the contract is unlocked\n error CurrencyNotSettled();\n\n /// @notice Thrown when trying to interact with a non-initialized pool\n error PoolNotInitialized();\n\n /// @notice Thrown when unlock is called, but the contract is already unlocked\n error AlreadyUnlocked();\n\n /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n error ManagerLocked();\n\n /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n error TickSpacingTooLarge(int24 tickSpacing);\n\n /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n error TickSpacingTooSmall(int24 tickSpacing);\n\n /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n /// or on a pool that does not have a dynamic swap fee.\n error UnauthorizedDynamicLPFeeUpdate();\n\n /// @notice Thrown when trying to swap amount of 0\n error SwapAmountCannotBeZero();\n\n ///@notice Thrown when native currency is passed to a non native settlement\n error NonzeroNativeValue();\n\n /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n error MustClearExactPositiveDelta();\n\n /// @notice Emitted when a new pool is initialized\n /// @param id The abi encoded hash of the pool key struct for the new pool\n /// @param currency0 The first currency of the pool by address sort order\n /// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none\n /// @param sqrtPriceX96 The price of the pool on initialization\n /// @param tick The initial tick of the pool corresponding to the initialized price\n event Initialize(\n PoolId indexed id,\n Currency indexed currency0,\n Currency indexed currency1,\n uint24 fee,\n int24 tickSpacing,\n IHooks hooks,\n uint160 sqrtPriceX96,\n int24 tick\n );\n\n /// @notice Emitted when a liquidity position is modified\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that modified the pool\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param liquidityDelta The amount of liquidity that was added or removed\n /// @param salt The extra data to make positions unique\n event ModifyLiquidity(\n PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n );\n\n /// @notice Emitted for swaps between currency0 and currency1\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param amount0 The delta of the currency0 balance of the pool\n /// @param amount1 The delta of the currency1 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 the price of the pool after the swap\n /// @param fee The swap fee in hundredths of a bip\n event Swap(\n PoolId indexed id,\n address indexed sender,\n int128 amount0,\n int128 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick,\n uint24 fee\n );\n\n /// @notice Emitted for donations\n /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n /// @param sender The address that initiated the donate call\n /// @param amount0 The amount donated in currency0\n /// @param amount1 The amount donated in currency1\n event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n function unlock(bytes calldata data) external returns (bytes memory);\n\n /// @notice Initialize the state for a given pool ID\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The pool key for the pool to initialize\n /// @param sqrtPriceX96 The initial square root price\n /// @return tick The initial tick of the pool\n function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n /// @notice Modify the liquidity for the given pool\n /// @dev Poke by calling with a zero liquidityDelta\n /// @param key The pool to modify liquidity in\n /// @param params The parameters for modifying the liquidity\n /// @param hookData The data to pass through to the add/removeLiquidity hooks\n /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n /// @notice Swap against the given pool\n /// @param key The pool to swap in\n /// @param params The parameters for swapping\n /// @param hookData The data to pass through to the swap hooks\n /// @return swapDelta The balance delta of the address swapping\n /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta swapDelta);\n\n /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n /// Donors should keep this in mind when designing donation mechanisms.\n /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n /// Read the comments in `Pool.swap()` for more information about this.\n /// @param key The key of the pool to donate to\n /// @param amount0 The amount of currency0 to donate\n /// @param amount1 The amount of currency1 to donate\n /// @param hookData The data to pass through to the donate hooks\n /// @return BalanceDelta The delta of the caller after the donate\n function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n external\n returns (BalanceDelta);\n\n /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n /// for native tokens because the amount to settle is determined by the sent value.\n /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n /// native funds, this function can be called with the native currency to then be able to settle the native currency\n function sync(Currency currency) external;\n\n /// @notice Called by the user to net out some value owed to the user\n /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n /// @dev Can also be used as a mechanism for free flash loans\n /// @param currency The currency to withdraw from the pool manager\n /// @param to The address to withdraw to\n /// @param amount The amount of currency to withdraw\n function take(Currency currency, address to, uint256 amount) external;\n\n /// @notice Called by the user to pay what is owed\n /// @return paid The amount of currency settled\n function settle() external payable returns (uint256 paid);\n\n /// @notice Called by the user to pay on behalf of another address\n /// @param recipient The address to credit for the payment\n /// @return paid The amount of currency settled\n function settleFor(address recipient) external payable returns (uint256 paid);\n\n /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n /// @dev This could be used to clear a balance that is considered dust.\n /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n function clear(Currency currency, uint256 amount) external;\n\n /// @notice Called by the user to move value into ERC6909 balance\n /// @param to The address to mint the tokens to\n /// @param id The currency address to mint to ERC6909s, as a uint256\n /// @param amount The amount of currency to mint\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function mint(address to, uint256 id, uint256 amount) external;\n\n /// @notice Called by the user to move value from ERC6909 balance\n /// @param from The address to burn the tokens from\n /// @param id The currency address to burn from ERC6909s, as a uint256\n /// @param amount The amount of currency to burn\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function burn(address from, uint256 id, uint256 amount) external;\n\n /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The key of the pool to update dynamic LP fees for\n /// @param newDynamicLPFee The new dynamic pool LP fee\n function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IProtocolFees.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n /// @notice Thrown when protocol fee is set too high\n error ProtocolFeeTooLarge(uint24 fee);\n\n /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n error InvalidCaller();\n\n /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n error ProtocolFeeCurrencySynced();\n\n /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n /// @notice Emitted when the protocol fee is updated for a pool.\n event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n /// @notice Given a currency address, returns the protocol fees accrued in that currency\n /// @param currency The currency to check\n /// @return amount The amount of protocol fees accrued in the currency\n function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n /// @notice Sets the protocol fee for the given pool\n /// @param key The key of the pool to set a protocol fee for\n /// @param newProtocolFee The fee to set\n function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n /// @notice Sets the protocol fee controller\n /// @param controller The new protocol fee controller\n function setProtocolFeeController(address controller) external;\n\n /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n /// @dev This will revert if the contract is unlocked\n /// @param recipient The address to receive the protocol fees\n /// @param currency The currency to withdraw\n /// @param amount The amount of currency to withdraw\n /// @return amountCollected The amount of currency successfully withdrawn\n function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n external\n returns (uint256 amountCollected);\n\n /// @notice Returns the current protocol fee controller address\n /// @return address The current protocol fee controller address\n function protocolFeeController() external view returns (address);\n}\n" + }, + "@uniswap/v4-core/src/libraries/CustomRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n /// @dev ERC-7751 error for wrapping bubbled up reverts\n error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n /// @dev Reverts with the selector of a custom error in the scratch space\n function revertWith(bytes4 selector) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n revert(0, 0x04)\n }\n }\n\n /// @dev Reverts with a custom error with an address argument in the scratch space\n function revertWith(bytes4 selector, address addr) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with an int24 argument in the scratch space\n function revertWith(bytes4 selector, int24 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, signextend(2, value))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n function revertWith(bytes4 selector, uint160 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with two int24 arguments\n function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), signextend(2, value1))\n mstore(add(fmp, 0x24), signextend(2, value2))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two uint160 arguments\n function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two address arguments\n function revertWith(bytes4 selector, address value1, address value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n /// @dev this method can be vulnerable to revert data bombs\n function bubbleUpAndRevertWith(\n address revertingContract,\n bytes4 revertingFunctionSelector,\n bytes4 additionalContext\n ) internal pure {\n bytes4 wrappedErrorSelector = WrappedError.selector;\n assembly (\"memory-safe\") {\n // Ensure the size of the revert data is a multiple of 32 bytes\n let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n let fmp := mload(0x40)\n\n // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n mstore(fmp, wrappedErrorSelector)\n mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(\n add(fmp, 0x24),\n and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n // offset revert reason\n mstore(add(fmp, 0x44), 0x80)\n // offset additional context\n mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n // size revert reason\n mstore(add(fmp, 0x84), returndatasize())\n // revert reason\n returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n // size additional context\n mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n // additional context\n mstore(\n add(fmp, add(0xc4, encodedDataSize)),\n and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n revert(fmp, add(0xe4, encodedDataSize))\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/FixedPoint128.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n" + }, + "@uniswap/v4-core/src/libraries/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) internal pure returns (uint256 result) {\n unchecked {\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 = a * b; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(a, b, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n assembly (\"memory-safe\") {\n result := div(prod0, denominator)\n }\n return result;\n }\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 (\"memory-safe\") {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly (\"memory-safe\") {\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 = (0 - denominator) & denominator;\n // Divide denominator by power of two\n assembly (\"memory-safe\") {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly (\"memory-safe\") {\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 (\"memory-safe\") {\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 preconditions 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\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) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) != 0) {\n require(++result > 0);\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n assembly (\"memory-safe\") {\n z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n if shr(128, z) {\n // revert SafeCastOverflow()\n mstore(0, 0x93dafdf1)\n revert(0x1c, 0x04)\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/Position.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n using CustomRevert for bytes4;\n\n /// @notice Cannot update a position with no liquidity\n error CannotUpdateEmptyPosition();\n\n // info stored for each user's position\n struct State {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n }\n\n /// @notice Returns the State struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range\n /// @return position The position info struct of the given owners' position\n function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n view\n returns (State storage position)\n {\n bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n position = self[positionKey];\n }\n\n /// @notice A helper function to calculate the position key\n /// @param owner The address of the position owner\n /// @param tickLower the lower tick boundary of the position\n /// @param tickUpper the upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n pure\n returns (bytes32 positionKey)\n {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n mstore(fmp, owner) // [0x0c, 0x20)\n positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n // now clean the memory we used\n mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n mstore(fmp, 0) // fmp held owner\n }\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n /// @return feesOwed0 The amount of currency0 owed to the position owner\n /// @return feesOwed1 The amount of currency1 owed to the position owner\n function update(\n State storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n uint128 liquidity = self.liquidity;\n\n if (liquidityDelta == 0) {\n // disallow pokes for 0 liquidity positions\n if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n } else {\n self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n unchecked {\n feesOwed0 =\n FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n feesOwed1 =\n FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n }\n\n // update the position\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n using CustomRevert for bytes4;\n\n error SafeCastOverflow();\n\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint160\n function toUint160(uint256 x) internal pure returns (uint160 y) {\n y = uint160(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a uint128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint128\n function toUint128(uint256 x) internal pure returns (uint128 y) {\n y = uint128(x);\n if (x != y) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n /// @param x The int128 to be casted\n /// @return y The casted integer, now type uint128\n function toUint128(int128 x) internal pure returns (uint128 y) {\n if (x < 0) SafeCastOverflow.selector.revertWith();\n y = uint128(x);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param x The int256 to be downcasted\n /// @return y The downcasted integer, now type int128\n function toInt128(int256 x) internal pure returns (int128 y) {\n y = int128(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param x The uint256 to be casted\n /// @return y The casted integer, now type int256\n function toInt256(uint256 x) internal pure returns (int256 y) {\n y = int256(x);\n if (y < 0) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return The downcasted integer, now type int128\n function toInt128(uint256 x) internal pure returns (int128) {\n if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n return int128(int256(x));\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/StateLibrary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n /// @notice index of pools mapping in the PoolManager\n bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n /// @notice index of feeGrowthGlobal0X128 in Pool.State\n uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n /// @notice index of liquidity in Pool.State\n uint256 public constant LIQUIDITY_OFFSET = 3;\n\n /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n uint256 public constant TICKS_OFFSET = 4;\n\n /// @notice index of tickBitmap mapping in Pool.State\n uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n uint256 public constant POSITIONS_OFFSET = 6;\n\n /**\n * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n * @dev Corresponds to pools[poolId].slot0\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n * @return tick The current tick of the pool.\n * @return protocolFee The protocol fee of the pool.\n * @return lpFee The swap fee of the pool.\n */\n function getSlot0(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n bytes32 data = manager.extsload(stateSlot);\n\n // 24 bits |24bits|24bits |24 bits|160 bits\n // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n // ---------- | fee |protocolfee | tick | sqrtPriceX96\n assembly (\"memory-safe\") {\n // bottom 160 bits of data\n sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n // next 24 bits of data\n tick := signextend(2, shr(160, data))\n // next 24 bits of data\n protocolFee := and(shr(184, data), 0xFFFFFF)\n // last 24 bits of data\n lpFee := and(shr(208, data), 0xFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the tick information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve information for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n )\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // read all 3 words of the TickInfo struct\n bytes32[] memory data = manager.extsload(slot, 3);\n assembly (\"memory-safe\") {\n let firstWord := mload(add(data, 32))\n liquidityNet := sar(128, firstWord)\n liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n feeGrowthOutside0X128 := mload(add(data, 64))\n feeGrowthOutside1X128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve liquidity for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n */\n function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint128 liquidityGross, int128 liquidityNet)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n bytes32 value = manager.extsload(slot);\n assembly (\"memory-safe\") {\n liquidityNet := sar(128, value)\n liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the fee growth outside a tick range of a pool\n * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve fee growth for.\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // offset by 1 word, since the first word is liquidityGross + liquidityNet\n bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n assembly (\"memory-safe\") {\n feeGrowthOutside0X128 := mload(add(data, 32))\n feeGrowthOutside1X128 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves the global fee growth of a pool.\n * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return feeGrowthGlobal0 The global fee growth for token0.\n * @return feeGrowthGlobal1 The global fee growth for token1.\n * @dev Note that feeGrowthGlobal can be artificially inflated\n * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n */\n function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State, `uint256 feeGrowthGlobal0X128`\n bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n // read the 2 words of feeGrowthGlobal\n bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n assembly (\"memory-safe\") {\n feeGrowthGlobal0 := mload(add(data, 32))\n feeGrowthGlobal1 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves total the liquidity of a pool.\n * @dev Corresponds to pools[poolId].liquidity\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return liquidity The liquidity of the pool.\n */\n function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `uint128 liquidity`\n bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Retrieves the tick bitmap of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].tickBitmap[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve the bitmap for.\n * @return tickBitmap The bitmap of the tick.\n */\n function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n internal\n view\n returns (uint256 tickBitmap)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n tickBitmap = uint256(manager.extsload(slot));\n }\n\n /**\n * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param poolId The ID of the pool.\n * @param owner The owner of the liquidity position.\n * @param tickLower The lower tick of the liquidity range.\n * @param tickUpper The upper tick of the liquidity range.\n * @param salt The bytes32 randomness to further distinguish position state.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(\n IPoolManager manager,\n PoolId poolId,\n address owner,\n int24 tickLower,\n int24 tickUpper,\n bytes32 salt\n ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n }\n\n /**\n * @notice Retrieves the position information of a pool at a specific position ID.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n // read all 3 words of the Position.State struct\n bytes32[] memory data = manager.extsload(slot, 3);\n\n assembly (\"memory-safe\") {\n liquidity := mload(add(data, 32))\n feeGrowthInside0LastX128 := mload(add(data, 64))\n feeGrowthInside1LastX128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity of a position.\n * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n */\n function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Calculate the fee growth inside a tick range of a pool\n * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tickLower The lower tick of the range.\n * @param tickUpper The upper tick of the range.\n * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n */\n function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n internal\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n {\n (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickLower);\n (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickUpper);\n (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n unchecked {\n if (tickCurrent < tickLower) {\n feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n } else if (tickCurrent >= tickUpper) {\n feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n }\n }\n }\n\n function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n }\n\n function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int24 => TickInfo) ticks`\n bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n // slot key of the tick key: `pools[poolId].ticks[tick]\n return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n }\n\n function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(bytes32 => Position.State) positions;`\n bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n // slot of the mapping key: `pools[poolId].positions[positionId]\n return keccak256(abi.encodePacked(positionId, positionMapping));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BalanceDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n assembly (\"memory-safe\") {\n balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := add(a0, b0)\n res1 := add(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := sub(a0, b0)\n res1 := sub(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n /// @notice A BalanceDelta of 0\n BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n assembly (\"memory-safe\") {\n _amount0 := sar(128, balanceDelta)\n }\n }\n\n function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n assembly (\"memory-safe\") {\n _amount1 := signextend(15, balanceDelta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BeforeSwapDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n pure\n returns (BeforeSwapDelta beforeSwapDelta)\n{\n assembly (\"memory-safe\") {\n beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n /// @notice A BeforeSwapDelta of 0\n BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap\n function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n assembly (\"memory-safe\") {\n deltaSpecified := sar(128, delta)\n }\n }\n\n /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap and afterSwap\n function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n assembly (\"memory-safe\") {\n deltaUnspecified := signextend(15, delta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/Currency.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n error NativeTransferFailed();\n\n /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n error ERC20TransferFailed();\n\n /// @notice A constant to represent the native currency\n Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n function transfer(Currency currency, address to, uint256 amount) internal {\n // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n // modified custom error selectors\n\n bool success;\n if (currency.isAddressZero()) {\n assembly (\"memory-safe\") {\n // Transfer the ETH and revert if it fails.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n // revert with NativeTransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n }\n } else {\n assembly (\"memory-safe\") {\n // Get a pointer to some free memory.\n let fmp := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n success :=\n and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), currency, 0, fmp, 68, 0, 32)\n )\n\n // Now clean the memory we used\n mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n }\n // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(\n Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n );\n }\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return address(this).balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n }\n }\n\n function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return owner.balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n }\n }\n\n function isAddressZero(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n }\n\n function toId(Currency currency) internal pure returns (uint256) {\n return uint160(Currency.unwrap(currency));\n }\n\n // If the upper 12 bytes are non-zero, they will be zero-ed out\n // Therefore, fromId() and toId() are not inverses of each other\n function fromId(uint256 id) internal pure returns (Currency) {\n return Currency.wrap(address(uint160(id)));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolId.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n assembly (\"memory-safe\") {\n // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n poolId := keccak256(poolKey, 0xa0)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolKey.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n /// @notice The lower currency of the pool, sorted numerically\n Currency currency0;\n /// @notice The higher currency of the pool, sorted numerically\n Currency currency1;\n /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n uint24 fee;\n /// @notice Ticks that involve positions must be a multiple of tick spacing\n int24 tickSpacing;\n /// @notice The hooks of the pool\n IHooks hooks;\n}\n" + }, + "@uniswap/v4-core/src/types/PoolOperation.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // how to modify the liquidity\n int256 liquidityDelta;\n // a value to set if you want unique liquidity positions at the same range\n bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n /// Whether to swap token0 for token1 or vice versa\n bool zeroForOne;\n /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n int256 amountSpecified;\n /// The sqrt price at which, if reached, the swap will stop executing\n uint160 sqrtPriceLimitX96;\n}\n" + }, + "contracts/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\n}\n" + }, + "contracts/interfaces/defi/IAerodromePool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAerodromePool\n * @notice Defines the basic interface for an Aerodrome Pool.\n */\ninterface IAerodromePool {\n function lastObservation() external view returns (uint256, uint256, uint256);\n function observationLength() external view returns (uint256 );\n\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/ILenderCommitmentGroup_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V3 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n bytes calldata _priceAdapterRoute\n\n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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/IUniswapV4Pool.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 IUniswapV4Pool 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/interfaces/uniswapv4/IImmutableState.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n /// @notice The Uniswap v4 PoolManager contract\n function poolManager() external view returns (IPoolManager);\n}" + }, + "contracts/interfaces/uniswapv4/IStateView.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {PoolId} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {Position} from \"@uniswap/v4-core/src/libraries/Position.sol\";\nimport {IImmutableState} from \"./IImmutableState.sol\";\n\n/// @title IStateView\n/// @notice Interface for the StateView contract\ninterface IStateView is IImmutableState {\n /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n /// @dev Corresponds to pools[poolId].slot0\n /// @param poolId The ID of the pool.\n /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n /// @return tick The current tick of the pool.\n /// @return protocolFee The protocol fee of the pool.\n /// @return lpFee The swap fee of the pool.\n function getSlot0(PoolId poolId)\n external\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);\n\n /// @notice Retrieves the tick information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve information for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickInfo(PoolId poolId, int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n );\n\n /// @notice Retrieves the liquidity information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve liquidity for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function getTickLiquidity(PoolId poolId, int24 tick)\n external\n view\n returns (uint128 liquidityGross, int128 liquidityNet);\n\n /// @notice Retrieves the fee growth outside a tick range of a pool\n /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve fee growth for.\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickFeeGrowthOutside(PoolId poolId, int24 tick)\n external\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128);\n\n /// @notice Retrieves the global fee growth of a pool.\n /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n /// @param poolId The ID of the pool.\n /// @return feeGrowthGlobal0 The global fee growth for token0.\n /// @return feeGrowthGlobal1 The global fee growth for token1.\n function getFeeGrowthGlobals(PoolId poolId)\n external\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1);\n\n /// @notice Retrieves the total liquidity of a pool.\n /// @dev Corresponds to pools[poolId].liquidity\n /// @param poolId The ID of the pool.\n /// @return liquidity The liquidity of the pool.\n function getLiquidity(PoolId poolId) external view returns (uint128 liquidity);\n\n /// @notice Retrieves the tick bitmap of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].tickBitmap[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve the bitmap for.\n /// @return tickBitmap The bitmap of the tick.\n function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap);\n\n /// @notice Retrieves the position info without needing to calculate the `positionId`.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param owner The owner of the liquidity position.\n /// @param tickLower The lower tick of the liquidity range.\n /// @param tickUpper The upper tick of the liquidity range.\n /// @param salt The bytes32 randomness to further distinguish position state.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the position information of a pool at a specific position ID.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, bytes32 positionId)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the liquidity of a position.\n /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity);\n\n /// @notice Calculate the fee growth inside a tick range of a pool\n /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside\n /// @param poolId The ID of the pool.\n /// @param tickLower The lower tick of the range.\n /// @param tickUpper The upper tick of the range.\n /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper)\n external\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V3.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\n\n} " + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.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 import \"../../../interfaces/IPriceAdapter.sol\";\n\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\nimport {FixedPointQ96} from \"../../../libraries/FixedPointQ96.sol\";\n\n\n\nimport \"../../../libraries/uniswap/TickMath.sol\";\nimport \"../../../libraries/uniswap/FixedPoint96.sol\";\nimport \"../../../libraries/uniswap/FullMath.sol\";\n \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\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_Pool_V3 is\n ILenderCommitmentGroup_V3,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\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 PRICE_ADAPTER;\n \n \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 bytes32 public priceRouteHash;\n \n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW \n\n\n uint256 public lastUnpausedAt;\n bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n\n\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n\n address _priceAdapter\n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n\n PRICE_ADAPTER = _priceAdapter;\n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _priceAdapterRoute Route configuration for the principal/collateral oracle.\n\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n bytes calldata _priceAdapterRoute\n\n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \n\n \n\n \n //internally this does checks and might revert \n // we register the price route with the adapter and save it locally \n priceRouteHash = IPriceAdapter( PRICE_ADAPTER ).registerPriceRoute(\n _priceAdapterRoute\n );\n\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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\n \n // principalPerCollateralAmount\n uint256 priceRatioQ96 = IPriceAdapter( PRICE_ADAPTER )\n .getPriceRatioQ96(priceRouteHash);\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 priceRatioQ96 // principalPerCollateralAmount \n );\n }\n\n \n \n\n /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 \n \n ) internal view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n FixedPointQ96.Q96,\n _maxPrincipalPerCollateralAmountQ96,\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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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 \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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Sets the delay time for withdrawing shares. 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 , \"WD\");\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"FDM\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"IC\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\");\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAerodrome.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAerodromePool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n import {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n\n\ncontract PriceAdapterAerodrome is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n // hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n // store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \n\n\n if (twapInterval == 0 ){\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\n\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \n }\n\n\n \n // Get two observations: current and one from twapInterval seconds ago\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = 0; // current\n secondsAgos[1] = twapInterval + 0 ; // oldest\n \n\n // Fetch observations\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\n\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\n\n // Calculate time-weighted average reserves\n uint256 timeElapsed = timestamp0 - timestamp1 ;\n require(timeElapsed > 0, \"Invalid time elapsed\");\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\n \n \n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\n\n\n\n\n }\n\n\n\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n\n }\n\n\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/*\n\n see https://docs.uniswap.org/contracts/v4/deployments \n\n\n https://docs.uniswap.org/contracts/v4/guides/read-pool-state\n\n\n\n*/\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\n\nimport {IStateView} from \"../interfaces/uniswapv4/IStateView.sol\";\n \nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\n\n\n\n\ncontract PriceAdapterUniswapV4 is\n IPriceAdapter\n\n{ \n\n \n\n using PoolIdLibrary for PoolKey;\n\n IPoolManager public immutable poolManager;\n\n\n using StateLibrary for IPoolManager;\n // address immutable POOL_MANAGER_V4; \n\n\n // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet \n //address immutable UNISWAP_V4_STATE_VIEW; \n\n struct PoolRoute {\n PoolId pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n \n\n constructor(IPoolManager _poolManager) {\n poolManager = _poolManager;\n }\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n function getPoolState(PoolId poolId) internal view returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint24 protocolFee,\n uint24 lpFee\n ) {\n return poolManager.getSlot0(poolId);\n }\n\n\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(PoolId poolId, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , ) = getPoolState(poolId);\n } else {\n\n revert(\"twap price not impl \");\n\n \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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 a08a7621537766baa9390006791ba1e85ab15f4a Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:24:20 -0500 Subject: [PATCH 23/46] deployed to base --- .../contracts/.openzeppelin/unknown-8453.json | 511 +++++ .../deploy/pricing/price_adapter_aerodrome.ts | 16 +- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 ++ .../base/LenderCommitmentGroupBeaconV3.json | 1893 +++++++++++++++++ .../base/LenderCommitmentGroupFactory_V3.json | 218 ++ .../base/PriceAdapterAerodrome.json | 239 +++ .../aa8b36c3500f06f65707aa97290d90c3.json | 986 +++++++++ 8 files changed, 3998 insertions(+), 3 deletions(-) create mode 100644 packages/contracts/deployments/base/FixedPointQ96.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json create mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json create mode 100644 packages/contracts/deployments/base/solcInputs/aa8b36c3500f06f65707aa97290d90c3.json diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index b8f35c0bb..b70764afa 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -114,6 +114,11 @@ "address": "0x48EA70BCe76FE2F0c79B29Bf852a1DCF957982aa", "txHash": "0x99bcdd5255ef14b7f295a8517d4e5072f15c8eb8059613fe2990c073902cf638", "kind": "transparent" + }, + { + "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", + "txHash": "0x420f803329e45b530043eebaac3da230ff153d995ebd396e67ef2fab7b9681f8", + "kind": "transparent" } ], "impls": { @@ -7918,6 +7923,512 @@ "types": {}, "namespaces": {} } + }, + "b3b2ef84dc3d78ec1e7c891362c8a6c587afc8bced8981ce1305a0c2ec3f0d0a": { + "address": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f", + "txHash": "0xb7f395487a8c1294cce9794b882de37a9125a5ac5bd0bf1a0dbfdd92e37638a1", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_status", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" + }, + { + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" + }, + { + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" + }, + { + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" + }, + { + "label": "poolSharesLastTransferredAt", + "offset": 0, + "slot": "201", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)50_storage", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" + }, + { + "label": "priceAdapter", + "offset": 0, + "slot": "252", + "type": "t_address", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:115" + }, + { + "label": "principalToken", + "offset": 0, + "slot": "253", + "type": "t_contract(IERC20)3312", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:119" + }, + { + "label": "collateralToken", + "offset": 0, + "slot": "254", + "type": "t_contract(IERC20)3312", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:120" + }, + { + "label": "marketId", + "offset": 0, + "slot": "255", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:122" + }, + { + "label": "totalPrincipalTokensCommitted", + "offset": 0, + "slot": "256", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:125" + }, + { + "label": "totalPrincipalTokensWithdrawn", + "offset": 0, + "slot": "257", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:126" + }, + { + "label": "totalPrincipalTokensLended", + "offset": 0, + "slot": "258", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:128" + }, + { + "label": "totalPrincipalTokensRepaid", + "offset": 0, + "slot": "259", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:129" + }, + { + "label": "excessivePrincipalTokensRepaid", + "offset": 0, + "slot": "260", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:130" + }, + { + "label": "totalInterestCollected", + "offset": 0, + "slot": "261", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:132" + }, + { + "label": "liquidityThresholdPercent", + "offset": 0, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:134" + }, + { + "label": "collateralRatio", + "offset": 2, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:135" + }, + { + "label": "maxLoanDuration", + "offset": 4, + "slot": "262", + "type": "t_uint32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:137" + }, + { + "label": "interestRateLowerBound", + "offset": 8, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:138" + }, + { + "label": "interestRateUpperBound", + "offset": 10, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:139" + }, + { + "label": "activeBids", + "offset": 0, + "slot": "263", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:147" + }, + { + "label": "activeBidsAmountDueRemaining", + "offset": 0, + "slot": "264", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:148" + }, + { + "label": "tokenDifferenceFromLiquidations", + "offset": 0, + "slot": "265", + "type": "t_int256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:150" + }, + { + "label": "firstDepositMade", + "offset": 0, + "slot": "266", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:152" + }, + { + "label": "withdrawDelayTimeSeconds", + "offset": 0, + "slot": "267", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:153" + }, + { + "label": "priceRouteHash", + "offset": 0, + "slot": "268", + "type": "t_bytes32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:157" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "offset": 0, + "slot": "269", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:161" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "270", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:164" + }, + { + "label": "paused", + "offset": 0, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:165" + }, + { + "label": "borrowingPaused", + "offset": 1, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:166" + }, + { + "label": "liquidationAuctionPaused", + "offset": 2, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:167" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)45_storage": { + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "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_contract(IERC20)3312": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_int256": { + "label": "int256", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "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": {} + } + }, + "c0994cac2d4f19b7af67e484cb25e90e135c727a1315840028c31cd9f47b8a50": { + "address": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", + "txHash": "0x702ed8bca3a1a7ea5111d2a308472cf540e716c2c70ac255f80454142946f959", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "lenderGroupBeacon", + "offset": 0, + "slot": "101", + "type": "t_address", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:32" + }, + { + "label": "deployedLenderGroupContracts", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:36" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } } } } diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 5dfd757f4..0bc64b39e 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -2,14 +2,26 @@ import { DeployFunction } from 'hardhat-deploy/dist/types' const deployFn: DeployFunction = async (hre) => { - + const { deployer } = await hre.getNamedAccounts() + + // Deploy FixedPointQ96 library first + const FixedPointQ96 = await hre.deployments.deploy('FixedPointQ96', { + from: deployer, + }) + + hre.log('FixedPointQ96 library deployed at:', FixedPointQ96.address) + + // Deploy PriceAdapterAerodrome with linked library const PriceAdapterAerodrome = await hre.deployments.deploy('PriceAdapterAerodrome', { from: deployer, + libraries: { + FixedPointQ96: FixedPointQ96.address, + }, }) - hre.log('Deploying PriceAdapterAerodrome') + hre.log('PriceAdapterAerodrome deployed at:', PriceAdapterAerodrome.address) } diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index b54efb620..11230905c 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,5 +42,7 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216 + "timelock-controller:update-delay-7200": 1757524216, + "lender-commitment-group-beacon-v3:deploy": 1763507914, + "lender-commitment-group-factory-v3:deploy": 1763507918 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json new file mode 100644 index 000000000..9efa4f679 --- /dev/null +++ b/packages/contracts/deployments/base/FixedPointQ96.json @@ -0,0 +1,134 @@ +{ + "address": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "divideFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "q96Value", + "type": "uint256" + } + ], + "name": "fromFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "multiplyFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "numerator", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "denominator", + "type": "uint256" + } + ], + "name": "toFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + } + ], + "transactionHash": "0x97f41b33e8ce419467acffb28d84e2e864568c9a49be1c4dfb0bb83c9dc430a4", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", + "transactionIndex": 0, + "gasUsed": "141837", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x1104b28a841f29ecaa9727fd025892864a7da9e87e1f671067653c5195c26a15", + "transactionHash": "0x97f41b33e8ce419467acffb28d84e2e864568c9a49be1c4dfb0bb83c9dc430a4", + "logs": [], + "blockNumber": 38358502, + "cumulativeGasUsed": "141837", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", + "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "devdoc": { + "kind": "dev", + "methods": {}, + "title": "FixedPoint96", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json new file mode 100644 index 000000000..d1405c625 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json @@ -0,0 +1,1893 @@ +{ + "address": "0x97a51fc3B8C4182b6c0C0a0f905A8e4d42153947", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_WITHDRAW_DELAY_TIME", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "firstDepositMade", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapter" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceAdapter", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceRouteHash", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_seconds" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json new file mode 100644 index 000000000..5df913751 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json @@ -0,0 +1,218 @@ +{ + "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x420f803329e45b530043eebaac3da230ff153d995ebd396e67ef2fab7b9681f8", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x687bf953de315ee8cd908a6679564762e9109cc1fa38a11651a8c070a28566fb", + "blockNumber": 38358501 + }, + "numDeployments": 1, + "implementation": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json new file mode 100644 index 000000000..edc5a96b6 --- /dev/null +++ b/packages/contracts/deployments/base/PriceAdapterAerodrome.json @@ -0,0 +1,239 @@ +{ + "address": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xf9e23fd54296e0fb67c3c228084e08ab902a194f9f2fc424ebfc51e4d6be9e34", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", + "transactionIndex": 0, + "gasUsed": "993855", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x825dbf0680e636c8812ef68e12714fb22ae55886d04b61d2d0db09cde455ea8d", + "transactionHash": "0xf9e23fd54296e0fb67c3c228084e08ab902a194f9f2fc424ebfc51e4d6be9e34", + "logs": [], + "blockNumber": 38358503, + "cumulativeGasUsed": "993855", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b81526004810187905260248101829052909150731c644A1bCB658b718e76051cDE6A22cdb235a4fD90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 76889, + "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/solcInputs/aa8b36c3500f06f65707aa97290d90c3.json b/packages/contracts/deployments/base/solcInputs/aa8b36c3500f06f65707aa97290d90c3.json new file mode 100644 index 000000000..a4be41bed --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/aa8b36c3500f06f65707aa97290d90c3.json @@ -0,0 +1,986 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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" + }, + "@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns an account's balance in the token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n FUNCTIONS\n //////////////////////////////////////////////////////////////*/\n\n /// @notice Owner balance of an id.\n /// @param owner The address of the owner.\n /// @param id The id of the token.\n /// @return amount The balance of the token.\n function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n /// @notice Spender allowance of an id.\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @return amount The allowance of the token.\n function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n /// @notice Checks if a spender is approved by an owner as an operator\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @return approved The approval status.\n function isOperator(address owner, address spender) external view returns (bool approved);\n\n /// @notice Transfers an amount of an id from the caller to a receiver.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Transfers an amount of an id from a sender to a receiver.\n /// @param sender The address of the sender.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Approves an amount of an id to a spender.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always\n function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Sets or removes an operator for the caller.\n /// @param operator The address of the operator.\n /// @param approved The approval status.\n /// @return bool True, always\n function setOperator(address operator, bool approved) external returns (bool);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExtsload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n /// @notice Called by external contracts to access granular pool state\n /// @param slot Key of slot to sload\n /// @return value The value of the slot as bytes32\n function extsload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access granular pool state\n /// @param startSlot Key of slot to start sloading from\n /// @param nSlots Number of slots to load into return value\n /// @return values List of loaded values.\n function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n /// @notice Called by external contracts to access sparse pool state\n /// @param slots List of slots to SLOAD from.\n /// @return values List of loaded values.\n function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExttload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n /// @notice Called by external contracts to access transient storage of the contract\n /// @param slot Key of slot to tload\n /// @return value The value of the slot as bytes32\n function exttload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access sparse transient pool state\n /// @param slots List of slots to tload\n /// @return values List of loaded values\n function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IHooks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n /// @notice The hook called before the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @return bytes4 The function selector for the hook\n function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n /// @notice The hook called after the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @param tick The current tick after the state of a pool is initialized\n /// @return bytes4 The function selector for the hook\n function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n external\n returns (bytes4);\n\n /// @notice The hook called before liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n external\n returns (bytes4, BeforeSwapDelta, uint24);\n\n /// @notice The hook called after a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterSwap(\n address sender,\n PoolKey calldata key,\n SwapParams calldata params,\n BalanceDelta delta,\n bytes calldata hookData\n ) external returns (bytes4, int128);\n\n /// @notice The hook called before donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function afterDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IPoolManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n /// @notice Thrown when a currency is not netted out after the contract is unlocked\n error CurrencyNotSettled();\n\n /// @notice Thrown when trying to interact with a non-initialized pool\n error PoolNotInitialized();\n\n /// @notice Thrown when unlock is called, but the contract is already unlocked\n error AlreadyUnlocked();\n\n /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n error ManagerLocked();\n\n /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n error TickSpacingTooLarge(int24 tickSpacing);\n\n /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n error TickSpacingTooSmall(int24 tickSpacing);\n\n /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n /// or on a pool that does not have a dynamic swap fee.\n error UnauthorizedDynamicLPFeeUpdate();\n\n /// @notice Thrown when trying to swap amount of 0\n error SwapAmountCannotBeZero();\n\n ///@notice Thrown when native currency is passed to a non native settlement\n error NonzeroNativeValue();\n\n /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n error MustClearExactPositiveDelta();\n\n /// @notice Emitted when a new pool is initialized\n /// @param id The abi encoded hash of the pool key struct for the new pool\n /// @param currency0 The first currency of the pool by address sort order\n /// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none\n /// @param sqrtPriceX96 The price of the pool on initialization\n /// @param tick The initial tick of the pool corresponding to the initialized price\n event Initialize(\n PoolId indexed id,\n Currency indexed currency0,\n Currency indexed currency1,\n uint24 fee,\n int24 tickSpacing,\n IHooks hooks,\n uint160 sqrtPriceX96,\n int24 tick\n );\n\n /// @notice Emitted when a liquidity position is modified\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that modified the pool\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param liquidityDelta The amount of liquidity that was added or removed\n /// @param salt The extra data to make positions unique\n event ModifyLiquidity(\n PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n );\n\n /// @notice Emitted for swaps between currency0 and currency1\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param amount0 The delta of the currency0 balance of the pool\n /// @param amount1 The delta of the currency1 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 the price of the pool after the swap\n /// @param fee The swap fee in hundredths of a bip\n event Swap(\n PoolId indexed id,\n address indexed sender,\n int128 amount0,\n int128 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick,\n uint24 fee\n );\n\n /// @notice Emitted for donations\n /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n /// @param sender The address that initiated the donate call\n /// @param amount0 The amount donated in currency0\n /// @param amount1 The amount donated in currency1\n event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n function unlock(bytes calldata data) external returns (bytes memory);\n\n /// @notice Initialize the state for a given pool ID\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The pool key for the pool to initialize\n /// @param sqrtPriceX96 The initial square root price\n /// @return tick The initial tick of the pool\n function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n /// @notice Modify the liquidity for the given pool\n /// @dev Poke by calling with a zero liquidityDelta\n /// @param key The pool to modify liquidity in\n /// @param params The parameters for modifying the liquidity\n /// @param hookData The data to pass through to the add/removeLiquidity hooks\n /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n /// @notice Swap against the given pool\n /// @param key The pool to swap in\n /// @param params The parameters for swapping\n /// @param hookData The data to pass through to the swap hooks\n /// @return swapDelta The balance delta of the address swapping\n /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta swapDelta);\n\n /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n /// Donors should keep this in mind when designing donation mechanisms.\n /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n /// Read the comments in `Pool.swap()` for more information about this.\n /// @param key The key of the pool to donate to\n /// @param amount0 The amount of currency0 to donate\n /// @param amount1 The amount of currency1 to donate\n /// @param hookData The data to pass through to the donate hooks\n /// @return BalanceDelta The delta of the caller after the donate\n function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n external\n returns (BalanceDelta);\n\n /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n /// for native tokens because the amount to settle is determined by the sent value.\n /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n /// native funds, this function can be called with the native currency to then be able to settle the native currency\n function sync(Currency currency) external;\n\n /// @notice Called by the user to net out some value owed to the user\n /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n /// @dev Can also be used as a mechanism for free flash loans\n /// @param currency The currency to withdraw from the pool manager\n /// @param to The address to withdraw to\n /// @param amount The amount of currency to withdraw\n function take(Currency currency, address to, uint256 amount) external;\n\n /// @notice Called by the user to pay what is owed\n /// @return paid The amount of currency settled\n function settle() external payable returns (uint256 paid);\n\n /// @notice Called by the user to pay on behalf of another address\n /// @param recipient The address to credit for the payment\n /// @return paid The amount of currency settled\n function settleFor(address recipient) external payable returns (uint256 paid);\n\n /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n /// @dev This could be used to clear a balance that is considered dust.\n /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n function clear(Currency currency, uint256 amount) external;\n\n /// @notice Called by the user to move value into ERC6909 balance\n /// @param to The address to mint the tokens to\n /// @param id The currency address to mint to ERC6909s, as a uint256\n /// @param amount The amount of currency to mint\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function mint(address to, uint256 id, uint256 amount) external;\n\n /// @notice Called by the user to move value from ERC6909 balance\n /// @param from The address to burn the tokens from\n /// @param id The currency address to burn from ERC6909s, as a uint256\n /// @param amount The amount of currency to burn\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function burn(address from, uint256 id, uint256 amount) external;\n\n /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The key of the pool to update dynamic LP fees for\n /// @param newDynamicLPFee The new dynamic pool LP fee\n function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IProtocolFees.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n /// @notice Thrown when protocol fee is set too high\n error ProtocolFeeTooLarge(uint24 fee);\n\n /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n error InvalidCaller();\n\n /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n error ProtocolFeeCurrencySynced();\n\n /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n /// @notice Emitted when the protocol fee is updated for a pool.\n event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n /// @notice Given a currency address, returns the protocol fees accrued in that currency\n /// @param currency The currency to check\n /// @return amount The amount of protocol fees accrued in the currency\n function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n /// @notice Sets the protocol fee for the given pool\n /// @param key The key of the pool to set a protocol fee for\n /// @param newProtocolFee The fee to set\n function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n /// @notice Sets the protocol fee controller\n /// @param controller The new protocol fee controller\n function setProtocolFeeController(address controller) external;\n\n /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n /// @dev This will revert if the contract is unlocked\n /// @param recipient The address to receive the protocol fees\n /// @param currency The currency to withdraw\n /// @param amount The amount of currency to withdraw\n /// @return amountCollected The amount of currency successfully withdrawn\n function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n external\n returns (uint256 amountCollected);\n\n /// @notice Returns the current protocol fee controller address\n /// @return address The current protocol fee controller address\n function protocolFeeController() external view returns (address);\n}\n" + }, + "@uniswap/v4-core/src/libraries/CustomRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n /// @dev ERC-7751 error for wrapping bubbled up reverts\n error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n /// @dev Reverts with the selector of a custom error in the scratch space\n function revertWith(bytes4 selector) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n revert(0, 0x04)\n }\n }\n\n /// @dev Reverts with a custom error with an address argument in the scratch space\n function revertWith(bytes4 selector, address addr) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with an int24 argument in the scratch space\n function revertWith(bytes4 selector, int24 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, signextend(2, value))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n function revertWith(bytes4 selector, uint160 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with two int24 arguments\n function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), signextend(2, value1))\n mstore(add(fmp, 0x24), signextend(2, value2))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two uint160 arguments\n function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two address arguments\n function revertWith(bytes4 selector, address value1, address value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n /// @dev this method can be vulnerable to revert data bombs\n function bubbleUpAndRevertWith(\n address revertingContract,\n bytes4 revertingFunctionSelector,\n bytes4 additionalContext\n ) internal pure {\n bytes4 wrappedErrorSelector = WrappedError.selector;\n assembly (\"memory-safe\") {\n // Ensure the size of the revert data is a multiple of 32 bytes\n let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n let fmp := mload(0x40)\n\n // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n mstore(fmp, wrappedErrorSelector)\n mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(\n add(fmp, 0x24),\n and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n // offset revert reason\n mstore(add(fmp, 0x44), 0x80)\n // offset additional context\n mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n // size revert reason\n mstore(add(fmp, 0x84), returndatasize())\n // revert reason\n returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n // size additional context\n mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n // additional context\n mstore(\n add(fmp, add(0xc4, encodedDataSize)),\n and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n revert(fmp, add(0xe4, encodedDataSize))\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/FixedPoint128.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n" + }, + "@uniswap/v4-core/src/libraries/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) internal pure returns (uint256 result) {\n unchecked {\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 = a * b; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(a, b, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n assembly (\"memory-safe\") {\n result := div(prod0, denominator)\n }\n return result;\n }\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 (\"memory-safe\") {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly (\"memory-safe\") {\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 = (0 - denominator) & denominator;\n // Divide denominator by power of two\n assembly (\"memory-safe\") {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly (\"memory-safe\") {\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 (\"memory-safe\") {\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 preconditions 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\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) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) != 0) {\n require(++result > 0);\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n assembly (\"memory-safe\") {\n z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n if shr(128, z) {\n // revert SafeCastOverflow()\n mstore(0, 0x93dafdf1)\n revert(0x1c, 0x04)\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/Position.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n using CustomRevert for bytes4;\n\n /// @notice Cannot update a position with no liquidity\n error CannotUpdateEmptyPosition();\n\n // info stored for each user's position\n struct State {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n }\n\n /// @notice Returns the State struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range\n /// @return position The position info struct of the given owners' position\n function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n view\n returns (State storage position)\n {\n bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n position = self[positionKey];\n }\n\n /// @notice A helper function to calculate the position key\n /// @param owner The address of the position owner\n /// @param tickLower the lower tick boundary of the position\n /// @param tickUpper the upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n pure\n returns (bytes32 positionKey)\n {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n mstore(fmp, owner) // [0x0c, 0x20)\n positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n // now clean the memory we used\n mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n mstore(fmp, 0) // fmp held owner\n }\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n /// @return feesOwed0 The amount of currency0 owed to the position owner\n /// @return feesOwed1 The amount of currency1 owed to the position owner\n function update(\n State storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n uint128 liquidity = self.liquidity;\n\n if (liquidityDelta == 0) {\n // disallow pokes for 0 liquidity positions\n if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n } else {\n self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n unchecked {\n feesOwed0 =\n FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n feesOwed1 =\n FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n }\n\n // update the position\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n using CustomRevert for bytes4;\n\n error SafeCastOverflow();\n\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint160\n function toUint160(uint256 x) internal pure returns (uint160 y) {\n y = uint160(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a uint128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint128\n function toUint128(uint256 x) internal pure returns (uint128 y) {\n y = uint128(x);\n if (x != y) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n /// @param x The int128 to be casted\n /// @return y The casted integer, now type uint128\n function toUint128(int128 x) internal pure returns (uint128 y) {\n if (x < 0) SafeCastOverflow.selector.revertWith();\n y = uint128(x);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param x The int256 to be downcasted\n /// @return y The downcasted integer, now type int128\n function toInt128(int256 x) internal pure returns (int128 y) {\n y = int128(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param x The uint256 to be casted\n /// @return y The casted integer, now type int256\n function toInt256(uint256 x) internal pure returns (int256 y) {\n y = int256(x);\n if (y < 0) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return The downcasted integer, now type int128\n function toInt128(uint256 x) internal pure returns (int128) {\n if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n return int128(int256(x));\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/StateLibrary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n /// @notice index of pools mapping in the PoolManager\n bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n /// @notice index of feeGrowthGlobal0X128 in Pool.State\n uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n /// @notice index of liquidity in Pool.State\n uint256 public constant LIQUIDITY_OFFSET = 3;\n\n /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n uint256 public constant TICKS_OFFSET = 4;\n\n /// @notice index of tickBitmap mapping in Pool.State\n uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n uint256 public constant POSITIONS_OFFSET = 6;\n\n /**\n * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n * @dev Corresponds to pools[poolId].slot0\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n * @return tick The current tick of the pool.\n * @return protocolFee The protocol fee of the pool.\n * @return lpFee The swap fee of the pool.\n */\n function getSlot0(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n bytes32 data = manager.extsload(stateSlot);\n\n // 24 bits |24bits|24bits |24 bits|160 bits\n // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n // ---------- | fee |protocolfee | tick | sqrtPriceX96\n assembly (\"memory-safe\") {\n // bottom 160 bits of data\n sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n // next 24 bits of data\n tick := signextend(2, shr(160, data))\n // next 24 bits of data\n protocolFee := and(shr(184, data), 0xFFFFFF)\n // last 24 bits of data\n lpFee := and(shr(208, data), 0xFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the tick information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve information for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n )\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // read all 3 words of the TickInfo struct\n bytes32[] memory data = manager.extsload(slot, 3);\n assembly (\"memory-safe\") {\n let firstWord := mload(add(data, 32))\n liquidityNet := sar(128, firstWord)\n liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n feeGrowthOutside0X128 := mload(add(data, 64))\n feeGrowthOutside1X128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve liquidity for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n */\n function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint128 liquidityGross, int128 liquidityNet)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n bytes32 value = manager.extsload(slot);\n assembly (\"memory-safe\") {\n liquidityNet := sar(128, value)\n liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the fee growth outside a tick range of a pool\n * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve fee growth for.\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // offset by 1 word, since the first word is liquidityGross + liquidityNet\n bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n assembly (\"memory-safe\") {\n feeGrowthOutside0X128 := mload(add(data, 32))\n feeGrowthOutside1X128 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves the global fee growth of a pool.\n * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return feeGrowthGlobal0 The global fee growth for token0.\n * @return feeGrowthGlobal1 The global fee growth for token1.\n * @dev Note that feeGrowthGlobal can be artificially inflated\n * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n */\n function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State, `uint256 feeGrowthGlobal0X128`\n bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n // read the 2 words of feeGrowthGlobal\n bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n assembly (\"memory-safe\") {\n feeGrowthGlobal0 := mload(add(data, 32))\n feeGrowthGlobal1 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves total the liquidity of a pool.\n * @dev Corresponds to pools[poolId].liquidity\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return liquidity The liquidity of the pool.\n */\n function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `uint128 liquidity`\n bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Retrieves the tick bitmap of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].tickBitmap[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve the bitmap for.\n * @return tickBitmap The bitmap of the tick.\n */\n function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n internal\n view\n returns (uint256 tickBitmap)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n tickBitmap = uint256(manager.extsload(slot));\n }\n\n /**\n * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param poolId The ID of the pool.\n * @param owner The owner of the liquidity position.\n * @param tickLower The lower tick of the liquidity range.\n * @param tickUpper The upper tick of the liquidity range.\n * @param salt The bytes32 randomness to further distinguish position state.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(\n IPoolManager manager,\n PoolId poolId,\n address owner,\n int24 tickLower,\n int24 tickUpper,\n bytes32 salt\n ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n }\n\n /**\n * @notice Retrieves the position information of a pool at a specific position ID.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n // read all 3 words of the Position.State struct\n bytes32[] memory data = manager.extsload(slot, 3);\n\n assembly (\"memory-safe\") {\n liquidity := mload(add(data, 32))\n feeGrowthInside0LastX128 := mload(add(data, 64))\n feeGrowthInside1LastX128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity of a position.\n * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n */\n function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Calculate the fee growth inside a tick range of a pool\n * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tickLower The lower tick of the range.\n * @param tickUpper The upper tick of the range.\n * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n */\n function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n internal\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n {\n (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickLower);\n (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickUpper);\n (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n unchecked {\n if (tickCurrent < tickLower) {\n feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n } else if (tickCurrent >= tickUpper) {\n feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n }\n }\n }\n\n function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n }\n\n function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int24 => TickInfo) ticks`\n bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n // slot key of the tick key: `pools[poolId].ticks[tick]\n return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n }\n\n function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(bytes32 => Position.State) positions;`\n bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n // slot of the mapping key: `pools[poolId].positions[positionId]\n return keccak256(abi.encodePacked(positionId, positionMapping));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BalanceDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n assembly (\"memory-safe\") {\n balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := add(a0, b0)\n res1 := add(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := sub(a0, b0)\n res1 := sub(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n /// @notice A BalanceDelta of 0\n BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n assembly (\"memory-safe\") {\n _amount0 := sar(128, balanceDelta)\n }\n }\n\n function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n assembly (\"memory-safe\") {\n _amount1 := signextend(15, balanceDelta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BeforeSwapDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n pure\n returns (BeforeSwapDelta beforeSwapDelta)\n{\n assembly (\"memory-safe\") {\n beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n /// @notice A BeforeSwapDelta of 0\n BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap\n function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n assembly (\"memory-safe\") {\n deltaSpecified := sar(128, delta)\n }\n }\n\n /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap and afterSwap\n function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n assembly (\"memory-safe\") {\n deltaUnspecified := signextend(15, delta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/Currency.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n error NativeTransferFailed();\n\n /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n error ERC20TransferFailed();\n\n /// @notice A constant to represent the native currency\n Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n function transfer(Currency currency, address to, uint256 amount) internal {\n // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n // modified custom error selectors\n\n bool success;\n if (currency.isAddressZero()) {\n assembly (\"memory-safe\") {\n // Transfer the ETH and revert if it fails.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n // revert with NativeTransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n }\n } else {\n assembly (\"memory-safe\") {\n // Get a pointer to some free memory.\n let fmp := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n success :=\n and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), currency, 0, fmp, 68, 0, 32)\n )\n\n // Now clean the memory we used\n mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n }\n // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(\n Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n );\n }\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return address(this).balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n }\n }\n\n function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return owner.balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n }\n }\n\n function isAddressZero(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n }\n\n function toId(Currency currency) internal pure returns (uint256) {\n return uint160(Currency.unwrap(currency));\n }\n\n // If the upper 12 bytes are non-zero, they will be zero-ed out\n // Therefore, fromId() and toId() are not inverses of each other\n function fromId(uint256 id) internal pure returns (Currency) {\n return Currency.wrap(address(uint160(id)));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolId.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n assembly (\"memory-safe\") {\n // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n poolId := keccak256(poolKey, 0xa0)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolKey.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n /// @notice The lower currency of the pool, sorted numerically\n Currency currency0;\n /// @notice The higher currency of the pool, sorted numerically\n Currency currency1;\n /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n uint24 fee;\n /// @notice Ticks that involve positions must be a multiple of tick spacing\n int24 tickSpacing;\n /// @notice The hooks of the pool\n IHooks hooks;\n}\n" + }, + "@uniswap/v4-core/src/types/PoolOperation.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // how to modify the liquidity\n int256 liquidityDelta;\n // a value to set if you want unique liquidity positions at the same range\n bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n /// Whether to swap token0 for token1 or vice versa\n bool zeroForOne;\n /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n int256 amountSpecified;\n /// The sqrt price at which, if reached, the swap will stop executing\n uint160 sqrtPriceLimitX96;\n}\n" + }, + "contracts/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\n}\n" + }, + "contracts/interfaces/defi/IAerodromePool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAerodromePool\n * @notice Defines the basic interface for an Aerodrome Pool.\n */\ninterface IAerodromePool {\n function lastObservation() external view returns (uint256, uint256, uint256);\n function observationLength() external view returns (uint256 );\n\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/ILenderCommitmentGroup_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V3 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n\n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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/IUniswapV4Pool.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 IUniswapV4Pool 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/interfaces/uniswapv4/IImmutableState.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n /// @notice The Uniswap v4 PoolManager contract\n function poolManager() external view returns (IPoolManager);\n}" + }, + "contracts/interfaces/uniswapv4/IStateView.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {PoolId} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {Position} from \"@uniswap/v4-core/src/libraries/Position.sol\";\nimport {IImmutableState} from \"./IImmutableState.sol\";\n\n/// @title IStateView\n/// @notice Interface for the StateView contract\ninterface IStateView is IImmutableState {\n /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n /// @dev Corresponds to pools[poolId].slot0\n /// @param poolId The ID of the pool.\n /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n /// @return tick The current tick of the pool.\n /// @return protocolFee The protocol fee of the pool.\n /// @return lpFee The swap fee of the pool.\n function getSlot0(PoolId poolId)\n external\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);\n\n /// @notice Retrieves the tick information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve information for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickInfo(PoolId poolId, int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n );\n\n /// @notice Retrieves the liquidity information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve liquidity for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function getTickLiquidity(PoolId poolId, int24 tick)\n external\n view\n returns (uint128 liquidityGross, int128 liquidityNet);\n\n /// @notice Retrieves the fee growth outside a tick range of a pool\n /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve fee growth for.\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickFeeGrowthOutside(PoolId poolId, int24 tick)\n external\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128);\n\n /// @notice Retrieves the global fee growth of a pool.\n /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n /// @param poolId The ID of the pool.\n /// @return feeGrowthGlobal0 The global fee growth for token0.\n /// @return feeGrowthGlobal1 The global fee growth for token1.\n function getFeeGrowthGlobals(PoolId poolId)\n external\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1);\n\n /// @notice Retrieves the total liquidity of a pool.\n /// @dev Corresponds to pools[poolId].liquidity\n /// @param poolId The ID of the pool.\n /// @return liquidity The liquidity of the pool.\n function getLiquidity(PoolId poolId) external view returns (uint128 liquidity);\n\n /// @notice Retrieves the tick bitmap of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].tickBitmap[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve the bitmap for.\n /// @return tickBitmap The bitmap of the tick.\n function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap);\n\n /// @notice Retrieves the position info without needing to calculate the `positionId`.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param owner The owner of the liquidity position.\n /// @param tickLower The lower tick of the liquidity range.\n /// @param tickUpper The upper tick of the liquidity range.\n /// @param salt The bytes32 randomness to further distinguish position state.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the position information of a pool at a specific position ID.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, bytes32 positionId)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the liquidity of a position.\n /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity);\n\n /// @notice Calculate the fee growth inside a tick range of a pool\n /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside\n /// @param poolId The ID of the pool.\n /// @param tickLower The lower tick of the range.\n /// @param tickUpper The upper tick of the range.\n /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper)\n external\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V3.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\n\n} " + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.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 import \"../../../interfaces/IPriceAdapter.sol\";\n\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\nimport {FixedPointQ96} from \"../../../libraries/FixedPointQ96.sol\";\n\n\n\nimport \"../../../libraries/uniswap/TickMath.sol\";\nimport \"../../../libraries/uniswap/FixedPoint96.sol\";\nimport \"../../../libraries/uniswap/FullMath.sol\";\n \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\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_Pool_V3 is\n ILenderCommitmentGroup_V3,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\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 priceAdapter;\n \n \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 bytes32 public priceRouteHash;\n \n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW \n\n\n uint256 public lastUnpausedAt;\n bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n\n\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n\n \n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _priceAdapterRoute Route configuration for the principal/collateral oracle.\n\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n address _priceAdapter, \n \n bytes calldata _priceAdapterRoute\n\n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \n\n \n priceAdapter = _priceAdapter ;\n \n //internally this does checks and might revert \n // we register the price route with the adapter and save it locally \n priceRouteHash = IPriceAdapter( priceAdapter ).registerPriceRoute(\n _priceAdapterRoute\n );\n\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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\n \n // principalPerCollateralAmount\n uint256 priceRatioQ96 = IPriceAdapter( priceAdapter )\n .getPriceRatioQ96(priceRouteHash);\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 priceRatioQ96 // principalPerCollateralAmount \n );\n }\n\n \n \n\n /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 \n \n ) internal view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n FixedPointQ96.Q96,\n _maxPrincipalPerCollateralAmountQ96,\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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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 \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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Sets the delay time for withdrawing shares. 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 , \"WD\");\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"FDM\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"IC\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\");\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAerodrome.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAerodromePool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n import {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n\n\ncontract PriceAdapterAerodrome is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n // hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n // store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \n\n\n if (twapInterval == 0 ){\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\n\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \n }\n\n\n \n // Get two observations: current and one from twapInterval seconds ago\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = 0; // current\n secondsAgos[1] = twapInterval + 0 ; // oldest\n \n\n // Fetch observations\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\n\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\n\n // Calculate time-weighted average reserves\n uint256 timeElapsed = timestamp0 - timestamp1 ;\n require(timeElapsed > 0, \"Invalid time elapsed\");\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\n \n \n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\n\n\n\n\n }\n\n\n\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n\n }\n\n\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/*\n\n see https://docs.uniswap.org/contracts/v4/deployments \n\n\n https://docs.uniswap.org/contracts/v4/guides/read-pool-state\n\n\n\n*/\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\n\nimport {IStateView} from \"../interfaces/uniswapv4/IStateView.sol\";\n \nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\n\n\n\n\ncontract PriceAdapterUniswapV4 is\n IPriceAdapter\n\n{ \n\n \n\n using PoolIdLibrary for PoolKey;\n\n IPoolManager public immutable poolManager;\n\n\n using StateLibrary for IPoolManager;\n // address immutable POOL_MANAGER_V4; \n\n\n // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet \n //address immutable UNISWAP_V4_STATE_VIEW; \n\n struct PoolRoute {\n PoolId pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n \n\n constructor(IPoolManager _poolManager) {\n poolManager = _poolManager;\n }\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n function getPoolState(PoolId poolId) internal view returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint24 protocolFee,\n uint24 lpFee\n ) {\n return poolManager.getSlot0(poolId);\n }\n\n\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(PoolId poolId, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , ) = getPoolState(poolId);\n } else {\n\n revert(\"twap price not impl \");\n\n \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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 43646d0980071439b6b025a75fac14f019a8f819 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:24:52 -0500 Subject: [PATCH 24/46] reset deployments --- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 -- .../base/LenderCommitmentGroupBeaconV3.json | 1893 ----------------- .../base/LenderCommitmentGroupFactory_V3.json | 218 -- .../base/PriceAdapterAerodrome.json | 239 --- 5 files changed, 1 insertion(+), 2487 deletions(-) delete mode 100644 packages/contracts/deployments/base/FixedPointQ96.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json delete mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index 11230905c..b54efb620 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,7 +42,5 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216, - "lender-commitment-group-beacon-v3:deploy": 1763507914, - "lender-commitment-group-factory-v3:deploy": 1763507918 + "timelock-controller:update-delay-7200": 1757524216 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json deleted file mode 100644 index 9efa4f679..000000000 --- a/packages/contracts/deployments/base/FixedPointQ96.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "address": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", - "abi": [ - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "divideFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "q96Value", - "type": "uint256" - } - ], - "name": "fromFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "multiplyFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "numerator", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "denominator", - "type": "uint256" - } - ], - "name": "toFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - } - ], - "transactionHash": "0x97f41b33e8ce419467acffb28d84e2e864568c9a49be1c4dfb0bb83c9dc430a4", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", - "transactionIndex": 0, - "gasUsed": "141837", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x1104b28a841f29ecaa9727fd025892864a7da9e87e1f671067653c5195c26a15", - "transactionHash": "0x97f41b33e8ce419467acffb28d84e2e864568c9a49be1c4dfb0bb83c9dc430a4", - "logs": [], - "blockNumber": 38358502, - "cumulativeGasUsed": "141837", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", - "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "devdoc": { - "kind": "dev", - "methods": {}, - "title": "FixedPoint96", - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", - "version": 1 - }, - "storageLayout": { - "storage": [], - "types": null - } -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json deleted file mode 100644 index d1405c625..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json +++ /dev/null @@ -1,1893 +0,0 @@ -{ - "address": "0x97a51fc3B8C4182b6c0C0a0f905A8e4d42153947", - "abi": [ - { - "type": "constructor", - "stateMutability": "undefined", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_tellerV2" - }, - { - "type": "address", - "name": "_smartCommitmentForwarder" - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Approval", - "inputs": [ - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "address", - "name": "spender", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "BorrowerAcceptedFunds", - "inputs": [ - { - "type": "address", - "name": "borrower", - "indexed": true - }, - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "collateralAmount", - "indexed": false - }, - { - "type": "uint32", - "name": "loanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRate", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "DefaultedLoanLiquidated", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "liquidator", - "indexed": true - }, - { - "type": "uint256", - "name": "amountDue", - "indexed": false - }, - { - "type": "int256", - "name": "tokenAmountDifference", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Deposit", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "LoanRepaid", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "repayer", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "interestAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "totalPrincipalRepaid", - "indexed": false - }, - { - "type": "uint256", - "name": "totalInterestCollected", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Paused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PoolInitialized", - "inputs": [ - { - "type": "address", - "name": "principalTokenAddress", - "indexed": true - }, - { - "type": "address", - "name": "collateralTokenAddress", - "indexed": true - }, - { - "type": "uint256", - "name": "marketId", - "indexed": false - }, - { - "type": "uint32", - "name": "maxLoanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateLowerBound", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateUpperBound", - "indexed": false - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent", - "indexed": false - }, - { - "type": "uint16", - "name": "loanToValuePercent", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "SharesLastTransferredAt", - "inputs": [ - { - "type": "address", - "name": "recipient", - "indexed": true - }, - { - "type": "uint256", - "name": "transferredAt", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Transfer", - "inputs": [ - { - "type": "address", - "name": "from", - "indexed": true - }, - { - "type": "address", - "name": "to", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Unpaused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Withdraw", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "receiver", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "WithdrawFromEscrow", - "inputs": [ - { - "type": "uint256", - "name": "amount", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "EXCHANGE_RATE_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MAX_WITHDRAW_DELAY_TIME", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MIN_TWAP_INTERVAL", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "ORACLE_MANAGER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "SMART_COMMITMENT_FORWARDER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "TELLER_V2", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "UNISWAP_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "acceptFundsForAcceptBid", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_borrower" - }, - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "uint256", - "name": "_principalAmount" - }, - { - "type": "uint256", - "name": "_collateralAmount" - }, - { - "type": "address", - "name": "_collateralTokenAddress" - }, - { - "type": "uint256", - "name": "_collateralTokenId" - }, - { - "type": "uint32", - "name": "_loanDuration" - }, - { - "type": "uint16", - "name": "_interestRate" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "activeBids", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "activeBidsAmountDueRemaining", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "allowance", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - }, - { - "type": "address", - "name": "spender" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "approve", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "asset", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "assetTokenAddress" - } - ] - }, - { - "type": "function", - "name": "balanceOf", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "account" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "borrowingPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralRequiredToBorrowPrincipal", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "collateralTokensAmountToMatchValue" - } - ] - }, - { - "type": "function", - "name": "collateralRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "collateralToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToShares", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decimals", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decreaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "subtractedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deposit", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "excessivePrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "firstDepositMade", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenType", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getLastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMarketId", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMaxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinInterestRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "amountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amountOwed" - }, - { - "type": "uint256", - "name": "_loanDefaultedTimestamp" - } - ], - "outputs": [ - { - "type": "int256", - "name": "amountDifference_" - } - ] - }, - { - "type": "function", - "name": "getPoolUtilizationRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "activeLoansAmountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalAmountAvailableToBorrow", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getSharesLastTransferredAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getTokenDifferenceFromLiquidations", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "int256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "increaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "addedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "address", - "name": "_priceAdapter" - }, - { - "type": "bytes", - "name": "_priceAdapterRoute" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "interestRateLowerBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "interestRateUpperBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "lastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidateDefaultedLoanWithIncentive", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "int256", - "name": "_tokenAmountDifference" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "liquidationAuctionPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidityThresholdPercent", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxPrincipalPerCollateralAmount", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "mint", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "name", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "pauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "paused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceAdapter", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceRouteHash", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bytes32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "principalToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "redeem", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "repayLoanCallback", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "address", - "name": "repayer" - }, - { - "type": "uint256", - "name": "principalAmount" - }, - { - "type": "uint256", - "name": "interestAmount" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "setWithdrawDelayTime", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_seconds" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "sharesExchangeRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "sharesExchangeRateInverse", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "symbol", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalInterestCollected", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensCommitted", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensLended", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensWithdrawn", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalSupply", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transfer", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferFrom", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "from" - }, - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "withdraw", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "withdrawDelayTimeSeconds", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "withdrawFromEscrowVault", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amount" - } - ], - "outputs": [] - } - ], - "receipt": {}, - "numDeployments": 1, - "implementation": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json deleted file mode 100644 index 5df913751..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json +++ /dev/null @@ -1,218 +0,0 @@ -{ - "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", - "abi": [ - { - "type": "event", - "anonymous": false, - "name": "DeployedLenderGroupContract", - "inputs": [ - { - "type": "address", - "name": "groupContract", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "deployLenderCommitmentGroupPool", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_initialPrincipalAmount" - }, - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "tuple[]", - "name": "_poolOracleRoutes", - "components": [ - { - "type": "address", - "name": "pool" - }, - { - "type": "bool", - "name": "zeroForOne" - }, - { - "type": "uint32", - "name": "twapInterval" - }, - { - "type": "uint256", - "name": "token0Decimals" - }, - { - "type": "uint256", - "name": "token1Decimals" - } - ] - } - ], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deployedLenderGroupContracts", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_lenderGroupBeacon" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "lenderGroupBeacon", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - } - ], - "transactionHash": "0x420f803329e45b530043eebaac3da230ff153d995ebd396e67ef2fab7b9681f8", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "blockHash": "0x687bf953de315ee8cd908a6679564762e9109cc1fa38a11651a8c070a28566fb", - "blockNumber": 38358501 - }, - "numDeployments": 1, - "implementation": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json deleted file mode 100644 index edc5a96b6..000000000 --- a/packages/contracts/deployments/base/PriceAdapterAerodrome.json +++ /dev/null @@ -1,239 +0,0 @@ -{ - "address": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - }, - { - "indexed": false, - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "RouteRegistered", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "name": "decodePoolRoutes", - "outputs": [ - { - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "route_array", - "type": "tuple[]" - } - ], - "stateMutability": "pure", - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "routes", - "type": "tuple[]" - } - ], - "name": "encodePoolRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "encoded", - "type": "bytes" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "route", - "type": "bytes32" - } - ], - "name": "getPriceRatioQ96", - "outputs": [ - { - "internalType": "uint256", - "name": "priceRatioQ96", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "name": "priceRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "", - "type": "bytes" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "registerPriceRoute", - "outputs": [ - { - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "transactionHash": "0xf9e23fd54296e0fb67c3c228084e08ab902a194f9f2fc424ebfc51e4d6be9e34", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", - "transactionIndex": 0, - "gasUsed": "993855", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x825dbf0680e636c8812ef68e12714fb22ae55886d04b61d2d0db09cde455ea8d", - "transactionHash": "0xf9e23fd54296e0fb67c3c228084e08ab902a194f9f2fc424ebfc51e4d6be9e34", - "logs": [], - "blockNumber": 38358503, - "cumulativeGasUsed": "993855", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", - "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b81526004810187905260248101829052909150731c644A1bCB658b718e76051cDE6A22cdb235a4fD90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "libraries": { - "FixedPointQ96": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD" - }, - "devdoc": { - "kind": "dev", - "methods": {}, - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 76889, - "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", - "label": "priceRoutes", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_bytes32,t_bytes_storage)" - } - ], - "types": { - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_bytes_storage": { - "encoding": "bytes", - "label": "bytes", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_bytes_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bytes)", - "numberOfBytes": "32", - "value": "t_bytes_storage" - } - } - } -} \ No newline at end of file From 53cf89a3b1b615d0113b1eb05781421a6f0bfb39 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:28:58 -0500 Subject: [PATCH 25/46] reset deployment --- packages/contracts/.openzeppelin/unknown-8453.json | 5 +++++ .../contracts/deploy/pricing/price_adapter_aerodrome.ts | 8 +++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index b70764afa..6d3289ff8 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -119,6 +119,11 @@ "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", "txHash": "0x420f803329e45b530043eebaac3da230ff153d995ebd396e67ef2fab7b9681f8", "kind": "transparent" + }, + { + "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", + "txHash": "0x28718cd73d3d4489fc442288f552111a272b3ee8109c2b815768557c7d1454b2", + "kind": "transparent" } ], "impls": { diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 0bc64b39e..68c03d447 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -11,7 +11,8 @@ const deployFn: DeployFunction = async (hre) => { from: deployer, }) - hre.log('FixedPointQ96 library deployed at:', FixedPointQ96.address) + hre.log('FixedPointQ96 library deployed at:' ) + hre.log( FixedPointQ96.address) // Deploy PriceAdapterAerodrome with linked library const PriceAdapterAerodrome = await hre.deployments.deploy('PriceAdapterAerodrome', { @@ -21,7 +22,8 @@ const deployFn: DeployFunction = async (hre) => { }, }) - hre.log('PriceAdapterAerodrome deployed at:', PriceAdapterAerodrome.address) + hre.log('PriceAdapterAerodrome deployed at:' ) + hre.log( PriceAdapterAerodrome.address) } @@ -29,7 +31,7 @@ const deployFn: DeployFunction = async (hre) => { // tags and deployment deployFn.id = 'price-adapter-aerodrome:deploy' deployFn.tags = ['teller-v2', 'price-adapter-aerodrome:deploy'] -deployFn.dependencies = [''] +deployFn.dependencies = [] deployFn.skip = async (hre) => { return !hre.network.live || ![ 'base', ].includes(hre.network.name) From 5d1eb99469f32092a18aa04e2c152477dec9f216 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:30:11 -0500 Subject: [PATCH 26/46] reset deployment --- packages/contracts/.openzeppelin/unknown-8453.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index 6d3289ff8..12cc9fa6c 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -124,6 +124,11 @@ "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", "txHash": "0x28718cd73d3d4489fc442288f552111a272b3ee8109c2b815768557c7d1454b2", "kind": "transparent" + }, + { + "address": "0x1aA915AE93129053d507297dC19e1c5D170e08b4", + "txHash": "0x901a79fe8c8fbb7cb0ddfff000884f43724aa11790016bd6a45b5c10eb37a29c", + "kind": "transparent" } ], "impls": { From 3d6be3dbbc43da5d6b0d0b92cca107f8d9f99747 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:33:49 -0500 Subject: [PATCH 27/46] try to deploy --- .../contracts/.openzeppelin/unknown-8453.json | 409 ------------------ .../uniswap_pricing_libraryV2.ts | 1 + .../teller_v2/uniswap_pricing_library.ts | 4 +- .../deploy/teller_v2/v2_calculations.ts | 1 + 4 files changed, 5 insertions(+), 410 deletions(-) diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index 12cc9fa6c..026a705ce 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -7934,415 +7934,6 @@ "namespaces": {} } }, - "b3b2ef84dc3d78ec1e7c891362c8a6c587afc8bced8981ce1305a0c2ec3f0d0a": { - "address": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f", - "txHash": "0xb7f395487a8c1294cce9794b882de37a9125a5ac5bd0bf1a0dbfdd92e37638a1", - "layout": { - "solcVersion": "0.8.24", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_status", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_balances", - "offset": 0, - "slot": "151", - "type": "t_mapping(t_address,t_uint256)", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" - }, - { - "label": "_allowances", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" - }, - { - "label": "_totalSupply", - "offset": 0, - "slot": "153", - "type": "t_uint256", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" - }, - { - "label": "_name", - "offset": 0, - "slot": "154", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" - }, - { - "label": "_symbol", - "offset": 0, - "slot": "155", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" - }, - { - "label": "__gap", - "offset": 0, - "slot": "156", - "type": "t_array(t_uint256)45_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" - }, - { - "label": "poolSharesLastTransferredAt", - "offset": 0, - "slot": "201", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)50_storage", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" - }, - { - "label": "priceAdapter", - "offset": 0, - "slot": "252", - "type": "t_address", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:115" - }, - { - "label": "principalToken", - "offset": 0, - "slot": "253", - "type": "t_contract(IERC20)3312", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:119" - }, - { - "label": "collateralToken", - "offset": 0, - "slot": "254", - "type": "t_contract(IERC20)3312", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:120" - }, - { - "label": "marketId", - "offset": 0, - "slot": "255", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:122" - }, - { - "label": "totalPrincipalTokensCommitted", - "offset": 0, - "slot": "256", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:125" - }, - { - "label": "totalPrincipalTokensWithdrawn", - "offset": 0, - "slot": "257", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:126" - }, - { - "label": "totalPrincipalTokensLended", - "offset": 0, - "slot": "258", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:128" - }, - { - "label": "totalPrincipalTokensRepaid", - "offset": 0, - "slot": "259", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:129" - }, - { - "label": "excessivePrincipalTokensRepaid", - "offset": 0, - "slot": "260", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:130" - }, - { - "label": "totalInterestCollected", - "offset": 0, - "slot": "261", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:132" - }, - { - "label": "liquidityThresholdPercent", - "offset": 0, - "slot": "262", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:134" - }, - { - "label": "collateralRatio", - "offset": 2, - "slot": "262", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:135" - }, - { - "label": "maxLoanDuration", - "offset": 4, - "slot": "262", - "type": "t_uint32", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:137" - }, - { - "label": "interestRateLowerBound", - "offset": 8, - "slot": "262", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:138" - }, - { - "label": "interestRateUpperBound", - "offset": 10, - "slot": "262", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:139" - }, - { - "label": "activeBids", - "offset": 0, - "slot": "263", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:147" - }, - { - "label": "activeBidsAmountDueRemaining", - "offset": 0, - "slot": "264", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:148" - }, - { - "label": "tokenDifferenceFromLiquidations", - "offset": 0, - "slot": "265", - "type": "t_int256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:150" - }, - { - "label": "firstDepositMade", - "offset": 0, - "slot": "266", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:152" - }, - { - "label": "withdrawDelayTimeSeconds", - "offset": 0, - "slot": "267", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:153" - }, - { - "label": "priceRouteHash", - "offset": 0, - "slot": "268", - "type": "t_bytes32", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:157" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "offset": 0, - "slot": "269", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:161" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "270", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:164" - }, - { - "label": "paused", - "offset": 0, - "slot": "271", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:165" - }, - { - "label": "borrowingPaused", - "offset": 1, - "slot": "271", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:166" - }, - { - "label": "liquidationAuctionPaused", - "offset": 2, - "slot": "271", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V3", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:167" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_uint256)45_storage": { - "label": "uint256[45]", - "numberOfBytes": "1440" - }, - "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_contract(IERC20)3312": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_int256": { - "label": "int256", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "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": {} - } - }, "c0994cac2d4f19b7af67e484cb25e90e135c727a1315840028c31cd9f47b8a50": { "address": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", "txHash": "0x702ed8bca3a1a7ea5111d2a308472cf540e716c2c70ac255f80454142946f959", 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 6be48ea39..369d87f76 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts @@ -4,6 +4,7 @@ const deployFn: DeployFunction = async (hre) => { const { deployer } = await hre.getNamedAccounts() const uniswapPricingLibraryV2 = await hre.deployments.deploy('UniswapPricingLibraryV2', { from: deployer, + skipIfAlreadyDeployed: true, }) } diff --git a/packages/contracts/deploy/teller_v2/uniswap_pricing_library.ts b/packages/contracts/deploy/teller_v2/uniswap_pricing_library.ts index 8bd6836d6..341ae8e77 100644 --- a/packages/contracts/deploy/teller_v2/uniswap_pricing_library.ts +++ b/packages/contracts/deploy/teller_v2/uniswap_pricing_library.ts @@ -4,11 +4,13 @@ const deployFn: DeployFunction = async (hre) => { const { deployer } = await hre.getNamedAccounts() const uniswapPricingLibrary = await hre.deployments.deploy('UniswapPricingLibrary', { from: deployer, + skipIfAlreadyDeployed: true, + }) } // tags and deployment deployFn.id = 'teller-v2:uniswap-pricing-library' deployFn.tags = ['teller-v2', 'teller-v2:uniswap-pricing-library'] -deployFn.dependencies = [''] +deployFn.dependencies = [] export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/teller_v2/v2_calculations.ts b/packages/contracts/deploy/teller_v2/v2_calculations.ts index b06ed7251..b660abc95 100644 --- a/packages/contracts/deploy/teller_v2/v2_calculations.ts +++ b/packages/contracts/deploy/teller_v2/v2_calculations.ts @@ -4,6 +4,7 @@ const deployFn: DeployFunction = async (hre) => { const { deployer } = await hre.getNamedAccounts() const v2Calculations = await hre.deployments.deploy('V2Calculations', { from: deployer, + skipIfAlreadyDeployed: true, }) } From 2705ffc22f30784848b45f2aab8e38044bb7dec4 Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:37:27 -0500 Subject: [PATCH 28/46] deployed contracts on base --- .../contracts/.openzeppelin/unknown-8453.json | 7934 +---------------- .../lender_commitment_group_v3_beacon.ts | 3 +- .../lender_groups_factory_v3.ts | 2 + .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 + .../base/LenderCommitmentGroupBeaconV3.json | 1893 ++++ .../base/LenderCommitmentGroupFactory_V3.json | 218 + .../base/PriceAdapterAerodrome.json | 239 + 8 files changed, 2497 insertions(+), 7930 deletions(-) create mode 100644 packages/contracts/deployments/base/FixedPointQ96.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json create mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index 026a705ce..8874c15c2 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -1,7942 +1,20 @@ { "manifestVersion": "3.2", "admin": { - "address": "0x001F15eF4a2Feb778823952af512F717811E4456", - "txHash": "0x15d665075ab3985e7c46fefff4bd6c63879ad5832b908aabd46dd24eee6b412f" + "address": "0x97a51fc3B8C4182b6c0C0a0f905A8e4d42153947", + "txHash": "0x17808e622942d7fc61cf88717e933b3346c5cee2b126101d85478e42b2f039e1" }, "proxies": [ { - "address": "0x8C406eD8De8837670f84047BE3314095942a0119", - "txHash": "0x28ada7878926e43337303a33aca90e244b40cac9656e1ac7238dc4ea48efcfb1", - "kind": "transparent" - }, - { - "address": "0x5cfD3aeD08a444Be32839bD911Ebecd688861164", - "txHash": "0x5280ad82dee76af5ab793c1daf34fc03df09455c7380289bcc66a6c61082ed52", - "kind": "transparent" - }, - { - "address": "0x71B04a8569914bCb99D5F95644CF6b089c826024", - "txHash": "0x41d51d62022ac83764d6962796e3eb0ba50233b84ebd226a500f664de1223a3d", - "kind": "transparent" - }, - { - "address": "0x7F5a9A32E2cE39652C5F148eBaaa7fBD1A39Cf23", - "txHash": "0x24f8e3f4f7bfdf66d4d439b38227a05f2720be2c68a29da026eead02992f0568", - "kind": "transparent" - }, - { - "address": "0x2bD9697bF0AB44bE5cA698fB5787d8F13ca48Ffc", - "txHash": "0xbcf1222e42f97e6a5470de8c822c4fcf2d08f09983b39001f88edf002052f9d9", - "kind": "transparent" - }, - { - "address": "0x84B550EE6959FA3F3A44498836F2A9473734ba78", - "txHash": "0x1c87df3fb4875c3f93027e36693dc7907e0a5ea5077bd6151071959837ebcb61", - "kind": "transparent" - }, - { - "address": "0x5594f9EE0DdF1e2D21ac8125dfeA66fc4c85Cd01", - "txHash": "0xef4a25fa0dc9299e134e7c3dec261b5e0cdf52ea5046c389dc5c99d6bb1b8e85", - "kind": "transparent" - }, - { - "address": "0xa8eC4511C5f7E8B0859b1e3BFF50641ecf98f30B", - "txHash": "0xe67c981c5d0b612b9ecf9b25860c913fc0dfb90244e4696aad35c7225160183b", - "kind": "transparent" - }, - { - "address": "0x18A6BcAd5e52cbecc34b987697FC7bE15eDF9599", - "txHash": "0x182877ddb2c0ea99661f15b1031ed84245740019e346ac5e093152b2ce7b6ad8", - "kind": "transparent" - }, - { - "address": "0xf236d5Cc4d45eA0eF223Bfdf9583e655f51C12fB", - "txHash": "0x13e7cc07a0fdec017bd4912d3b1a24bdbb13f1d071297cfb2677bc28bc25b185", - "kind": "transparent" - }, - { - "address": "0x7bFE23e80F9DfFBbb3E1FB613eB4F5a617073fa5", - "txHash": "0x2f4dc09bce25d612bdd53daab6fc2c650c2ecb22980816cf490548a6c1b77781", - "kind": "transparent" - }, - { - "address": "0xfA87381128aAF95fB637BbA0B760bA2f9970c2b5", - "txHash": "0x3c845e6ddde213bff741c08bf9c68d709659aafbbc91a021a2b1f2d115ba5aca", - "kind": "transparent" - }, - { - "address": "0x5d3eCF8877eDAB28e14bD7d243fA8B0fE416E95E", - "txHash": "0xca163455658de2c2ebf7ab1d244c48c8b71aea73bc7012947c53a2160104fc5c", - "kind": "transparent" - }, - { - "address": "0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed", - "txHash": "0x57eb9b825a6175536ac4577638ec235a7109dba0d5e6a9d33a48c18bdcb12e2b", - "kind": "transparent" - }, - { - "address": "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", - "txHash": "0xde247da726f917c8d1c249a19c3654d0d74453bfbcacbbe3f58c367bec7c52bf", - "kind": "transparent" - }, - { - "address": "0x0708480670BdE591e275B06Cd19EcaDFC93A1f16", - "txHash": "0x606b5f03d3a9afeb9031188f7fd4ed5b8057343d1241a5b6fbd52808058bc023", - "kind": "transparent" - }, - { - "address": "0x7FBCefE4aE4c0C9E70427D0B9F1504Ed39d141BC", - "txHash": "0xe0e5b932ee384911b5443ffc287b0205f5f9fbd6ac58df30a6e831e9591a0a6f", - "kind": "transparent" - }, - { - "address": "0x7f43c21D4FE1807BF2CF25e6F048A03b57226e03", - "txHash": "0xdeda0730bd046902ddab358e92402b183f5b9327b7401b97f3c983012d6e9b3c", - "kind": "transparent" - }, - { - "address": "0xC2a093B641496Ac8AA9d6a17f216ADF4a42FC9B6", - "txHash": "0x4b8f52d5cb452c35fda05eb89f90ab00cd6ef235b7cf4dfdb8249cfbb5010200", - "kind": "transparent" - }, - { - "address": "0x37F483C895C66d3eDb14AE88ea9bA52F937Eb002", - "txHash": "0xbbdec7f18fc607bd332f03a843e732c1cfeb3933e378e8d8c8eb1e600ded6b3e", - "kind": "transparent" - }, - { - "address": "0x0410535A1C3c59Ce477644f21662b5A96b4bA085", - "txHash": "0xcc6c4514c71cba49d46e54772af5944925f77fd94b235c729e47939a62e95869", - "kind": "transparent" - }, - { - "address": "0x48EA70BCe76FE2F0c79B29Bf852a1DCF957982aa", - "txHash": "0x99bcdd5255ef14b7f295a8517d4e5072f15c8eb8059613fe2990c073902cf638", - "kind": "transparent" - }, - { - "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", - "txHash": "0x420f803329e45b530043eebaac3da230ff153d995ebd396e67ef2fab7b9681f8", - "kind": "transparent" - }, - { - "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", - "txHash": "0x28718cd73d3d4489fc442288f552111a272b3ee8109c2b815768557c7d1454b2", - "kind": "transparent" - }, - { - "address": "0x1aA915AE93129053d507297dC19e1c5D170e08b4", - "txHash": "0x901a79fe8c8fbb7cb0ddfff000884f43724aa11790016bd6a45b5c10eb37a29c", + "address": "0x98eEbd694eE24935615BF18bA1ae75B2E486487f", + "txHash": "0xa8d2d589773b0db38e02cc7d27810432a440af30f9aaee53259319050b1f748a", "kind": "transparent" } ], "impls": { - "7a0365f1d2728c50c75bf178b78d68ce83ebd37a1f6995b18fee9abcd8efc30f": { - "address": "0xfF5c6530d761aB1Fa5E78e70C791A260Cfe85FbC", - "txHash": "0xa065b4cf7af91315d3e91cf70cf1ae97c894176b7f97137285a52913791737ae", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "bidId", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "CollateralEscrowV1", - "src": "contracts/escrow/CollateralEscrowV1.sol:16" - }, - { - "label": "collateralBalances", - "offset": 0, - "slot": "102", - "type": "t_mapping(t_address,t_struct(Collateral)26130_storage)", - "contract": "CollateralEscrowV1", - "src": "contracts/escrow/CollateralEscrowV1.sol:18" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_enum(CollateralType)26120": { - "label": "enum CollateralType", - "members": [ - "ERC20", - "ERC721", - "ERC1155" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_struct(Collateral)26130_storage)": { - "label": "mapping(address => struct Collateral)", - "numberOfBytes": "32" - }, - "t_struct(Collateral)26130_storage": { - "label": "struct Collateral", - "members": [ - { - "label": "_collateralType", - "type": "t_enum(CollateralType)26120", - "offset": 0, - "slot": "0" - }, - { - "label": "_amount", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "_tokenId", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "_collateralAddress", - "type": "t_address", - "offset": 0, - "slot": "3" - } - ], - "numberOfBytes": "128" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "032c39add4d0355222025ad6d0b242e0fa061dbd76a18f52856a1551a3cadfac": { - "address": "0xbC9a4E3377eeBB22d45208d6AA14E6A2c777Ef75", - "txHash": "0xe3a8bc73c67d55e883b016acd8e8959d5311bfaee7ca19e7f3a6b62f3cad0920", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "_HASHED_NAME", - "offset": 0, - "slot": "1", - "type": "t_bytes32", - "contract": "EIP712Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:32" - }, - { - "label": "_HASHED_VERSION", - "offset": 0, - "slot": "2", - "type": "t_bytes32", - "contract": "EIP712Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:33" - }, - { - "label": "__gap", - "offset": 0, - "slot": "3", - "type": "t_array(t_uint256)50_storage", - "contract": "EIP712Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:120" - }, - { - "label": "_nonces", - "offset": 0, - "slot": "53", - "type": "t_mapping(t_address,t_uint256)", - "contract": "MinimalForwarderUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:33" - }, - { - "label": "__gap", - "offset": 0, - "slot": "54", - "type": "t_array(t_uint256)49_storage", - "contract": "MinimalForwarderUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:84" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "8a7903b059df8258d169527f3216fa334b3666ac8a908920317793aa07149d6e": { - "address": "0xB914032Fe28Bce8921aC6AEcD88F6B03234DE32B", - "txHash": "0x433f803c62d79ecedc81ead9257a3786c5bd203ae314aa8a39f241695539f12f", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_protocolFee", - "offset": 0, - "slot": "101", - "type": "t_uint16", - "contract": "ProtocolFee", - "src": "contracts/ProtocolFee.sol:8" - }, - { - "label": "_paused", - "offset": 2, - "slot": "101", - "type": "t_bool", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" - }, - { - "label": "bidId", - "offset": 0, - "slot": "151", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:92" - }, - { - "label": "bids", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_uint256,t_struct(Bid)9745_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:95" - }, - { - "label": "borrowerBids", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_address,t_array(t_uint256)dyn_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:98" - }, - { - "label": "__lenderVolumeFilled", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_address,t_uint256)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:101" - }, - { - "label": "__totalVolumeFilled", - "offset": 0, - "slot": "155", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:104" - }, - { - "label": "__lendingTokensSet", - "offset": 0, - "slot": "156", - "type": "t_struct(AddressSet)5690_storage", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:107" - }, - { - "label": "marketRegistry", - "offset": 0, - "slot": "158", - "type": "t_contract(IMarketRegistry)10548", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:109" - }, - { - "label": "reputationManager", - "offset": 0, - "slot": "159", - "type": "t_contract(IReputationManager)10607", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:110" - }, - { - "label": "_borrowerBidsActive", - "offset": 0, - "slot": "160", - "type": "t_mapping(t_address,t_struct(UintSet)5847_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:113" - }, - { - "label": "bidDefaultDuration", - "offset": 0, - "slot": "161", - "type": "t_mapping(t_uint256,t_uint32)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:115" - }, - { - "label": "bidExpirationTime", - "offset": 0, - "slot": "162", - "type": "t_mapping(t_uint256,t_uint32)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:116" - }, - { - "label": "lenderVolumeFilled", - "offset": 0, - "slot": "163", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:120" - }, - { - "label": "totalVolumeFilled", - "offset": 0, - "slot": "164", - "type": "t_mapping(t_address,t_uint256)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:124" - }, - { - "label": "version", - "offset": 0, - "slot": "165", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:126" - }, - { - "label": "uris", - "offset": 0, - "slot": "166", - "type": "t_mapping(t_uint256,t_string_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:130" - }, - { - "label": "_trustedMarketForwarders", - "offset": 0, - "slot": "167", - "type": "t_mapping(t_uint256,t_address)", - "contract": "TellerV2Storage_G1", - "src": "contracts/TellerV2Storage.sol:135" - }, - { - "label": "_approvedForwarderSenders", - "offset": 0, - "slot": "168", - "type": "t_mapping(t_address,t_struct(AddressSet)5690_storage)", - "contract": "TellerV2Storage_G1", - "src": "contracts/TellerV2Storage.sol:137" - }, - { - "label": "lenderCommitmentForwarder", - "offset": 0, - "slot": "169", - "type": "t_address", - "contract": "TellerV2Storage_G2", - "src": "contracts/TellerV2Storage.sol:142" - }, - { - "label": "collateralManager", - "offset": 0, - "slot": "170", - "type": "t_contract(ICollateralManager)10059", - "contract": "TellerV2Storage_G3", - "src": "contracts/TellerV2Storage.sol:146" - }, - { - "label": "lenderManager", - "offset": 0, - "slot": "171", - "type": "t_contract(ILenderManager)10386", - "contract": "TellerV2Storage_G4", - "src": "contracts/TellerV2Storage.sol:151" - }, - { - "label": "bidPaymentCycleType", - "offset": 0, - "slot": "172", - "type": "t_mapping(t_uint256,t_enum(PaymentCycleType)12596)", - "contract": "TellerV2Storage_G4", - "src": "contracts/TellerV2Storage.sol:153" - }, - { - "label": "escrowVault", - "offset": 0, - "slot": "173", - "type": "t_contract(IEscrowVault)10372", - "contract": "TellerV2Storage_G5", - "src": "contracts/TellerV2Storage.sol:158" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "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_array(t_uint256)dyn_storage": { - "label": "uint256[]", - "numberOfBytes": "32" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_contract(ICollateralManager)10059": { - "label": "contract ICollateralManager", - "numberOfBytes": "20" - }, - "t_contract(IERC20)1999": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_contract(IEscrowVault)10372": { - "label": "contract IEscrowVault", - "numberOfBytes": "20" - }, - "t_contract(ILenderManager)10386": { - "label": "contract ILenderManager", - "numberOfBytes": "20" - }, - "t_contract(IMarketRegistry)10548": { - "label": "contract IMarketRegistry", - "numberOfBytes": "20" - }, - "t_contract(IReputationManager)10607": { - "label": "contract IReputationManager", - "numberOfBytes": "20" - }, - "t_enum(BidState)9717": { - "label": "enum BidState", - "members": [ - "NONEXISTENT", - "PENDING", - "CANCELLED", - "ACCEPTED", - "PAID", - "LIQUIDATED", - "CLOSED" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentCycleType)12596": { - "label": "enum PaymentCycleType", - "members": [ - "Seconds", - "Monthly" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentType)12593": { - "label": "enum PaymentType", - "members": [ - "EMI", - "Bullet" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_array(t_uint256)dyn_storage)": { - "label": "mapping(address => uint256[])", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_struct(AddressSet)5690_storage)": { - "label": "mapping(address => struct EnumerableSet.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_struct(UintSet)5847_storage)": { - "label": "mapping(address => struct EnumerableSet.UintSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_address)": { - "label": "mapping(uint256 => address)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_enum(PaymentCycleType)12596)": { - "label": "mapping(uint256 => enum PaymentCycleType)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_string_storage)": { - "label": "mapping(uint256 => string)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Bid)9745_storage)": { - "label": "mapping(uint256 => struct Bid)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint32)": { - "label": "mapping(uint256 => uint32)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)5690_storage": { - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)5375_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Bid)9745_storage": { - "label": "struct Bid", - "members": [ - { - "label": "borrower", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "receiver", - "type": "t_address", - "offset": 0, - "slot": "1" - }, - { - "label": "lender", - "type": "t_address", - "offset": 0, - "slot": "2" - }, - { - "label": "marketplaceId", - "type": "t_uint256", - "offset": 0, - "slot": "3" - }, - { - "label": "_metadataURI", - "type": "t_bytes32", - "offset": 0, - "slot": "4" - }, - { - "label": "loanDetails", - "type": "t_struct(LoanDetails)9762_storage", - "offset": 0, - "slot": "5" - }, - { - "label": "terms", - "type": "t_struct(Terms)9769_storage", - "offset": 0, - "slot": "10" - }, - { - "label": "state", - "type": "t_enum(BidState)9717", - "offset": 0, - "slot": "12" - }, - { - "label": "paymentType", - "type": "t_enum(PaymentType)12593", - "offset": 1, - "slot": "12" - } - ], - "numberOfBytes": "416" - }, - "t_struct(LoanDetails)9762_storage": { - "label": "struct LoanDetails", - "members": [ - { - "label": "lendingToken", - "type": "t_contract(IERC20)1999", - "offset": 0, - "slot": "0" - }, - { - "label": "principal", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "totalRepaid", - "type": "t_struct(Payment)9722_storage", - "offset": 0, - "slot": "2" - }, - { - "label": "timestamp", - "type": "t_uint32", - "offset": 0, - "slot": "4" - }, - { - "label": "acceptedTimestamp", - "type": "t_uint32", - "offset": 4, - "slot": "4" - }, - { - "label": "lastRepaidTimestamp", - "type": "t_uint32", - "offset": 8, - "slot": "4" - }, - { - "label": "loanDuration", - "type": "t_uint32", - "offset": 12, - "slot": "4" - } - ], - "numberOfBytes": "160" - }, - "t_struct(Payment)9722_storage": { - "label": "struct Payment", - "members": [ - { - "label": "principal", - "type": "t_uint256", - "offset": 0, - "slot": "0" - }, - { - "label": "interest", - "type": "t_uint256", - "offset": 0, - "slot": "1" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Set)5375_storage": { - "label": "struct EnumerableSet.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_struct(Terms)9769_storage": { - "label": "struct Terms", - "members": [ - { - "label": "paymentCycleAmount", - "type": "t_uint256", - "offset": 0, - "slot": "0" - }, - { - "label": "paymentCycle", - "type": "t_uint32", - "offset": 0, - "slot": "1" - }, - { - "label": "APR", - "type": "t_uint16", - "offset": 4, - "slot": "1" - } - ], - "numberOfBytes": "64" - }, - "t_struct(UintSet)5847_storage": { - "label": "struct EnumerableSet.UintSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)5375_storage", - "offset": 0, - "slot": "0" - } - ], - "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" - } - } - } - }, - "797b64d3b87c3178c44d57ca0bba037d86cf9710f40eb2d971cc017ba18a17ec": { - "address": "0xbDF19f0cbe53BCaC880C214411bC183d1cD8A9F8", - "txHash": "0x31def7b5ff68c200423af727b0ed72325d5b581256e14e684daa3da676f6fc2b", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "tellerV2", - "offset": 0, - "slot": "101", - "type": "t_contract(ITellerV2)25725", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:23" - }, - { - "label": "collateralEscrowBeacon", - "offset": 0, - "slot": "102", - "type": "t_address", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:24" - }, - { - "label": "_escrows", - "offset": 0, - "slot": "103", - "type": "t_mapping(t_uint256,t_address)", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:27" - }, - { - "label": "_bidCollaterals", - "offset": 0, - "slot": "104", - "type": "t_mapping(t_uint256,t_struct(CollateralInfo)13557_storage)", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:29" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "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_contract(ITellerV2)25725": { - "label": "contract ITellerV2", - "numberOfBytes": "20" - }, - "t_enum(CollateralType)26120": { - "label": "enum CollateralType", - "members": [ - "ERC20", - "ERC721", - "ERC1155" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_struct(Collateral)26130_storage)": { - "label": "mapping(address => struct Collateral)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_address)": { - "label": "mapping(uint256 => address)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(CollateralInfo)13557_storage)": { - "label": "mapping(uint256 => struct CollateralManager.CollateralInfo)", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)5049_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4734_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Collateral)26130_storage": { - "label": "struct Collateral", - "members": [ - { - "label": "_collateralType", - "type": "t_enum(CollateralType)26120", - "offset": 0, - "slot": "0" - }, - { - "label": "_amount", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "_tokenId", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "_collateralAddress", - "type": "t_address", - "offset": 0, - "slot": "3" - } - ], - "numberOfBytes": "128" - }, - "t_struct(CollateralInfo)13557_storage": { - "label": "struct CollateralManager.CollateralInfo", - "members": [ - { - "label": "collateralAddresses", - "type": "t_struct(AddressSet)5049_storage", - "offset": 0, - "slot": "0" - }, - { - "label": "collateralInfo", - "type": "t_mapping(t_address,t_struct(Collateral)26130_storage)", - "offset": 0, - "slot": "2" - } - ], - "numberOfBytes": "96" - }, - "t_struct(Set)4734_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_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "b3b40208b3aacd41f6cf178037b325c13c7ad33ea564255191a05151432db52b": { - "address": "0xe6774DAAEdf6e95b222CD3dE09456ec0a46672C4", - "txHash": "0x992c44b916d925fe883b9a9c6f44314ca29279bb04f75373002e48ee77e61736", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "balances", - "offset": 0, - "slot": "51", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "EscrowVault", - "src": "contracts/EscrowVault.sol:21" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_uint256)50_storage": { - "label": "uint256[50]", - "numberOfBytes": "1600" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "af09bd5495be68defee9e7d7daeb69c6eff8349327f9e0bd54ef2275c69f9f93": { - "address": "0x4B4B129FD2c40e1b05D4378F751B93Df6173A16C", - "txHash": "0x4346bc6c64319fea58ee0dccc882d9863805ddbefc269c7a19a547838f114cc1", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" - }, - { - "label": "lenderAttestationSchemaId", - "offset": 0, - "slot": "1", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:51" - }, - { - "label": "markets", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint256,t_struct(Marketplace)18319_storage)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:53" - }, - { - "label": "__uriToId", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_bytes32,t_uint256)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:54" - }, - { - "label": "marketCount", - "offset": 0, - "slot": "4", - "type": "t_uint256", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:55" - }, - { - "label": "_attestingSchemaId", - "offset": 0, - "slot": "5", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:56" - }, - { - "label": "borrowerAttestationSchemaId", - "offset": 0, - "slot": "6", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:57" - }, - { - "label": "version", - "offset": 0, - "slot": "7", - "type": "t_uint256", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:59" - }, - { - "label": "marketIsClosed", - "offset": 0, - "slot": "8", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:61" - }, - { - "label": "tellerAS", - "offset": 0, - "slot": "9", - "type": "t_contract(TellerAS)15638", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:63" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_contract(TellerAS)15638": { - "label": "contract TellerAS", - "numberOfBytes": "20" - }, - "t_enum(PaymentCycleType)27917": { - "label": "enum PaymentCycleType", - "members": [ - "Seconds", - "Monthly" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentType)27914": { - "label": "enum PaymentType", - "members": [ - "EMI", - "Bullet" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_bytes32)": { - "label": "mapping(address => bytes32)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Marketplace)18319_storage)": { - "label": "mapping(uint256 => struct MarketRegistry.Marketplace)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)13224_storage": { - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)12909_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Marketplace)18319_storage": { - "label": "struct MarketRegistry.Marketplace", - "members": [ - { - "label": "owner", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "metadataURI", - "type": "t_string_storage", - "offset": 0, - "slot": "1" - }, - { - "label": "marketplaceFeePercent", - "type": "t_uint16", - "offset": 0, - "slot": "2" - }, - { - "label": "lenderAttestationRequired", - "type": "t_bool", - "offset": 2, - "slot": "2" - }, - { - "label": "verifiedLendersForMarket", - "type": "t_struct(AddressSet)13224_storage", - "offset": 0, - "slot": "3" - }, - { - "label": "lenderAttestationIds", - "type": "t_mapping(t_address,t_bytes32)", - "offset": 0, - "slot": "5" - }, - { - "label": "paymentCycleDuration", - "type": "t_uint32", - "offset": 0, - "slot": "6" - }, - { - "label": "paymentDefaultDuration", - "type": "t_uint32", - "offset": 4, - "slot": "6" - }, - { - "label": "bidExpirationTime", - "type": "t_uint32", - "offset": 8, - "slot": "6" - }, - { - "label": "borrowerAttestationRequired", - "type": "t_bool", - "offset": 12, - "slot": "6" - }, - { - "label": "verifiedBorrowersForMarket", - "type": "t_struct(AddressSet)13224_storage", - "offset": 0, - "slot": "7" - }, - { - "label": "borrowerAttestationIds", - "type": "t_mapping(t_address,t_bytes32)", - "offset": 0, - "slot": "9" - }, - { - "label": "feeRecipient", - "type": "t_address", - "offset": 0, - "slot": "10" - }, - { - "label": "paymentType", - "type": "t_enum(PaymentType)27914", - "offset": 20, - "slot": "10" - }, - { - "label": "paymentCycleType", - "type": "t_enum(PaymentCycleType)27917", - "offset": 21, - "slot": "10" - } - ], - "numberOfBytes": "352" - }, - "t_struct(Set)12909_storage": { - "label": "struct EnumerableSet.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" - } - } - } - }, - "c3f0cd9400dc672c104e46b9bbe1dc66444f40a18738c1c864f8c8e2c91de2cb": { - "address": "0x08C12C6943C41D12572B8C39926C3Fca6Dd376F9", - "txHash": "0x5487a954f5b249762013773003ceb7b282c71cf6645b93835ec1864b95a52f6a", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "__gap", - "offset": 0, - "slot": "51", - "type": "t_array(t_uint256)50_storage", - "contract": "TellerV2MarketForwarder", - "src": "contracts/TellerV2MarketForwarder.sol:152" - }, - { - "label": "commitments", - "offset": 0, - "slot": "101", - "type": "t_mapping(t_uint256,t_struct(Commitment)16268_storage)", - "contract": "LenderCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder.sol:60" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "102", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder.sol:62" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "103", - "type": "t_mapping(t_uint256,t_struct(AddressSet)5049_storage)", - "contract": "LenderCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder.sol:65" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "104", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder.sol:68" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "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)16244": { - "label": "enum LenderCommitmentForwarder.CommitmentCollateralType", - "members": [ - "NONE", - "ERC20", - "ERC721", - "ERC1155", - "ERC721_ANY_ID", - "ERC1155_ANY_ID", - "ERC721_MERKLE_PROOF", - "ERC1155_MERKLE_PROOF" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)5049_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)16268_storage)": { - "label": "mapping(uint256 => struct LenderCommitmentForwarder.Commitment)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)5049_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4734_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)16268_storage": { - "label": "struct LenderCommitmentForwarder.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)16244", - "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(Set)4734_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" - } - } - } - }, - "2e6664d873db1423701c2ba4143701a1dbf199e8d9280e090c29397d8557aeef": { - "address": "0x5Bb23271A93433B13c13D19826bc155a00694B2E", - "txHash": "0x121a5cff1a18904875ef167fcb0fbeb3d21ac74f71f8b9ddc9bdcfb1e7574b18", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "__gap", - "offset": 0, - "slot": "101", - "type": "t_array(t_uint256)50_storage", - "contract": "ERC165Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol:41" - }, - { - "label": "_name", - "offset": 0, - "slot": "151", - "type": "t_string_storage", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:25" - }, - { - "label": "_symbol", - "offset": 0, - "slot": "152", - "type": "t_string_storage", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:28" - }, - { - "label": "_owners", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_address)", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:31" - }, - { - "label": "_balances", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_address,t_uint256)", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:34" - }, - { - "label": "_tokenApprovals", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_address)", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:37" - }, - { - "label": "_operatorApprovals", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:40" - }, - { - "label": "__gap", - "offset": 0, - "slot": "157", - "type": "t_array(t_uint256)44_storage", - "contract": "ERC721Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:514" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_uint256)44_storage": { - "label": "uint256[44]", - "numberOfBytes": "1408" - }, - "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_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_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_address)": { - "label": "mapping(uint256 => address)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "870e02eff43ebc9ae33b8e6f3a3b7b1816f4cb20bde31ddfaf45084a2d5840ae": { - "address": "0x1E36C7e9fDa74e84eA3F21F733C93903637601b3", - "txHash": "0x4cf917dd68a7ae63c158bd7a2c73b679fa300d2681c6c55f96d06d280355a2e6", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" - }, - { - "label": "tellerV2", - "offset": 2, - "slot": "0", - "type": "t_contract(ITellerV2)25725", - "contract": "ReputationManager", - "src": "contracts/ReputationManager.sol:17" - }, - { - "label": "_delinquencies", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_struct(UintSet)13381_storage)", - "contract": "ReputationManager", - "src": "contracts/ReputationManager.sol:18" - }, - { - "label": "_defaults", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_address,t_struct(UintSet)13381_storage)", - "contract": "ReputationManager", - "src": "contracts/ReputationManager.sol:19" - }, - { - "label": "_currentDelinquencies", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_address,t_struct(UintSet)13381_storage)", - "contract": "ReputationManager", - "src": "contracts/ReputationManager.sol:20" - }, - { - "label": "_currentDefaults", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_address,t_struct(UintSet)13381_storage)", - "contract": "ReputationManager", - "src": "contracts/ReputationManager.sol:21" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_contract(ITellerV2)25725": { - "label": "contract ITellerV2", - "numberOfBytes": "20" - }, - "t_mapping(t_address,t_struct(UintSet)13381_storage)": { - "label": "mapping(address => struct EnumerableSet.UintSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_struct(Set)12909_storage": { - "label": "struct EnumerableSet.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_struct(UintSet)13381_storage": { - "label": "struct EnumerableSet.UintSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)12909_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "3e4a18649e8fd0de4c97834fcf9c8c3a31e7a27a086215bf697c939b612b1808": { - "address": "0xAD9AcE8A1Ea7267DC2ab19bf4b10465D56D5eCF0", - "txHash": "0xd7c99b1daf413e8717a53c8f1e558948af14b0e203153ca45dfce24518e710c1", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "allocationCount", - "offset": 0, - "slot": "1", - "type": "t_uint256", - "contract": "MarketLiquidityRewards", - "src": "contracts/MarketLiquidityRewards.sol:31" - }, - { - "label": "allocatedRewards", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint256,t_struct(RewardAllocation)25266_storage)", - "contract": "MarketLiquidityRewards", - "src": "contracts/MarketLiquidityRewards.sol:34" - }, - { - "label": "rewardClaimedForBid", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))", - "contract": "MarketLiquidityRewards", - "src": "contracts/MarketLiquidityRewards.sol:37" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_enum(AllocationStrategy)25269": { - "label": "enum IMarketLiquidityRewards.AllocationStrategy", - "members": [ - "BORROWER", - "LENDER" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))": { - "label": "mapping(uint256 => mapping(uint256 => bool))", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(RewardAllocation)25266_storage)": { - "label": "mapping(uint256 => struct IMarketLiquidityRewards.RewardAllocation)", - "numberOfBytes": "32" - }, - "t_struct(RewardAllocation)25266_storage": { - "label": "struct IMarketLiquidityRewards.RewardAllocation", - "members": [ - { - "label": "allocator", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "rewardTokenAddress", - "type": "t_address", - "offset": 0, - "slot": "1" - }, - { - "label": "rewardTokenAmount", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "marketId", - "type": "t_uint256", - "offset": 0, - "slot": "3" - }, - { - "label": "requiredPrincipalTokenAddress", - "type": "t_address", - "offset": 0, - "slot": "4" - }, - { - "label": "requiredCollateralTokenAddress", - "type": "t_address", - "offset": 0, - "slot": "5" - }, - { - "label": "minimumCollateralPerPrincipalAmount", - "type": "t_uint256", - "offset": 0, - "slot": "6" - }, - { - "label": "rewardPerLoanPrincipalAmount", - "type": "t_uint256", - "offset": 0, - "slot": "7" - }, - { - "label": "bidStartTimeMin", - "type": "t_uint32", - "offset": 0, - "slot": "8" - }, - { - "label": "bidStartTimeMax", - "type": "t_uint32", - "offset": 4, - "slot": "8" - }, - { - "label": "allocationStrategy", - "type": "t_enum(AllocationStrategy)25269", - "offset": 8, - "slot": "8" - } - ], - "numberOfBytes": "288" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - } - } - }, - "c8af3c5904b5702db41d2723af659a70075e35f2bf56678edcea5cbd2bb97398": { - "address": "0x760E7d5AB07B6FED640041de8f209fCBD2F83DCe", - "txHash": "0x589ee87070eb3493b89a956dda7ae86d5e8e8396594891ebc2745ba11a62ffab", - "layout": { - "solcVersion": "0.8.9", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "__gap", - "offset": 0, - "slot": "51", - "type": "t_array(t_uint256)50_storage", - "contract": "TellerV2MarketForwarder_G2", - "src": "contracts/TellerV2MarketForwarder_G2.sol:149" - }, - { - "label": "commitments", - "offset": 0, - "slot": "101", - "type": "t_mapping(t_uint256,t_struct(Commitment)27883_storage)", - "contract": "LenderCommitmentForwarder_G2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G2.sol:26" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "102", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_G2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G2.sol:28" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "103", - "type": "t_mapping(t_uint256,t_struct(AddressSet)5136_storage)", - "contract": "LenderCommitmentForwarder_G2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G2.sol:31" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "104", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_G2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G2.sol:34" - }, - { - "label": "userExtensions", - "offset": 0, - "slot": "105", - "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": "106", - "type": "t_array(t_uint256)49_storage", - "contract": "ExtensionsContextUpgradeable", - "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:61" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "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)27859": { - "label": "enum ILenderCommitmentForwarder.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_struct(AddressSet)5136_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)27883_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder.Commitment)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)5136_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4821_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)27883_storage": { - "label": "struct ILenderCommitmentForwarder.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)27859", - "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(Set)4821_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" - } - } - } - }, - "89e3ad1bf71ab289d2a9da3633bd16c39a8a9d15541ed47477f4705c68b89e2d": { - "address": "0x193d59841945979e0AA7Cd7D62d7262285390073", - "txHash": "0x08f35c6cc0df7e2594bfc02fbb590aeb2afe8c52eccd558b6f83c05d60a9665b", - "layout": { - "solcVersion": "0.8.9", - "storage": [], - "types": {} - } - }, - "47dd5e0e45e1e67767ef31bcc4f79e8bba0e10f4f48fd4fedbd40da76ad37eb4": { - "address": "0x95742cE32E9036958195FC59263136C33038a71F", - "txHash": "0x0fea4795da6b3ab1683876034cd4f5223a8772ab8e402fac18878e984b27223b", - "layout": { - "solcVersion": "0.8.9", - "storage": [], - "types": {} - } - }, - "49a506fa8c7e3aa45b2519f6ea88846f37f24f316d91afa4014114e93188e144": { - "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", - "txHash": "0xb2430f2e521ad6f1c27ba3d3a8d6c70772d00dc9e1bd4857f4b44ba187820ae0", - "layout": { - "solcVersion": "0.8.9", - "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)30233_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:52" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:54" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)5136_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:57" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:60" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)30244_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:62" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:65" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)30244_storage)dyn_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)30209": { - "label": "enum ILenderCommitmentForwarder_U1.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)30244_storage)dyn_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)5136_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)30233_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)5136_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4821_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)30233_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)30209", - "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)30244_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)4821_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": {} - } - }, - "477b92d0974d9edc72aabc04fae6a94fdae996513d7c297253feee8422d18244": { - "address": "0x928685Fd2ce2A3E8909a9f473a85648Ca3689860", - "txHash": "0x066c0bbcaf0fe9948cda5610ba4dfeeb660317df690fca799d1d6dcf8b70a53e", - "layout": { - "solcVersion": "0.8.9", - "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)9670_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:52" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:54" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)2505_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:57" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:60" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)9681_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:62" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:65" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)9681_storage)dyn_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)9646": { - "label": "enum ILenderCommitmentForwarder_U1.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)9681_storage)dyn_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)2505_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)9670_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)2505_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)2190_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)9670_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)9646", - "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)9681_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)2190_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": {} - } - }, - "da1ba5fb1043eb38ee9cdb1baa8b1da1dc06d0a306759dcb2df364fdc4c9a112": { - "address": "0xe7768f28455eE81D7B415f4F5019A316c27AB445", - "txHash": "0xefea582be3d842a7d28514d875efddf8ace7402f410be42f6ebd990d8f96ac53", - "layout": { - "solcVersion": "0.8.9", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "7beb106ff82e0c578719b53af02dac0ff6cb01cf863531b45c250d4991cf2550": { - "address": "0xE11884953B18F8ddC55875CBDAb71b624779D3bB", - "txHash": "0x8a4d500f4c59875af1c75741a6ca84b7fbba02b6011ba1dd639534d9fd73d9e4", - "layout": { - "solcVersion": "0.8.9", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "8da817c4687ac23882c6dc030e5dd99e93108382d8bf4060fb3ae66f06c6bc3f": { - "address": "0xf7B14778035fEAF44540A0bC1D4ED859bCB28229", - "txHash": "0x6d101008e0d96e6387bcff33ef67d40a57e2663c803c49c9d108978b5eb3cdf1", - "layout": { - "solcVersion": "0.8.9", - "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)35328_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:53" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:55" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)5136_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:58" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:61" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)35339_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:63" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:65" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)35339_storage)dyn_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)35304": { - "label": "enum ILenderCommitmentForwarder_U1.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)35339_storage)dyn_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)5136_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)35328_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)5136_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4821_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)35328_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)35304", - "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)35339_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)4821_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": {} - } - }, - "759e2bc8de2c0c66b468c52194f883348ff33847ea29965c3f7e80aeada486f9": { - "address": "0x90D08f8Df66dFdE93801783FF7A36876453DAE75", - "txHash": "0x141836c24f36145b12cfd2245f920b53f89bfbf0e8940b0aef91a4e6f1350c2c", - "layout": { - "solcVersion": "0.8.9", - "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)9734_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:53" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:55" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)2505_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:58" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:61" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)9745_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:63" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:65" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)9745_storage)dyn_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)9710": { - "label": "enum ILenderCommitmentForwarder_U1.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)9745_storage)dyn_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)2505_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)9734_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)2505_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)2190_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)9734_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)9710", - "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)9745_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)2190_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": {} - } - }, - "4ba47e8d72b06c99e7c2970dec06daf1cb3f1222bdf84432e5ad07990d1c9232": { - "address": "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f", - "txHash": "0xf22872a490473e23877b3f770a250d02585af766da8dd4ed7746036020674249", - "layout": { - "solcVersion": "0.8.9", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "9bc621ecc47856d2c0aa2e9c5f1d91db2e46bda93cffd7a9d7fc72ede22aabe5": { - "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", - "txHash": "0x8860e12ef5e2101098f3e1360ef36cf6c0ae27337e2da3462e2db09d331aa5c3", - "layout": { - "solcVersion": "0.8.9", - "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)31577_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:53" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:55" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)4437_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:58" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:61" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)31588_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:63" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U1", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:65" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)31588_storage)dyn_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)31553": { - "label": "enum ILenderCommitmentForwarder_U1.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)31588_storage)dyn_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)4437_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)31577_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)4437_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4122_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)31577_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)31553", - "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)31588_storage": { - "label": "struct ILenderCommitmentForwarder_U1.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)4122_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": {} - } - }, - "9e631a801ead541b466189477ae1e6277cadd66be89de0b47ca219f30f3f1d39": { - "address": "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04", - "txHash": "0xc7a3ddcc26e7ebad18debd1c75e8719fbcf8dfd72b13fe05792222b3f5352f61", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "b56835998d32c9b2ea1f0403f830abe933e5edf9a36ae7edab9741fd132411c4": { - "address": "0x0D1047229B9851eACE463Fb25f27982a5127c20F", - "txHash": "0x84b29c50106bf7b39755e0f96a9b190d1500f84227b9b3caf8bcb8c4a61cf496", - "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": "__gap", - "offset": 0, - "slot": "151", - "type": "t_array(t_uint256)50_storage", - "contract": "TellerV2MarketForwarder_G3", - "src": "contracts/TellerV2MarketForwarder_G3.sol:59" - }, - { - "label": "_paused", - "offset": 0, - "slot": "201", - "type": "t_bool", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)49_storage", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" - }, - { - "label": "_status", - "offset": 0, - "slot": "251", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "252", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_owner", - "offset": 0, - "slot": "301", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "302", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "liquidationProtocolFeePercent", - "offset": 0, - "slot": "351", - "type": "t_uint256", - "contract": "SmartCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:88" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "352", - "type": "t_uint256", - "contract": "SmartCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:89" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_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_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "a760a0559589b65fa300274efaba5c6ccfbdc047e6bd04cc1c98130077da1ad4": { - "address": "0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515", - "txHash": "0xca39f44f6502e1285693b478a2b4a59fc61f13037ecce6fe4f90653c4af755b9", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_paused", - "offset": 0, - "slot": "101", - "type": "t_bool", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" - }, - { - "label": "_status", - "offset": 0, - "slot": "151", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "152", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "poolSharesToken", - "offset": 0, - "slot": "201", - "type": "t_contract(LenderCommitmentGroupShares)26509", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:113" - }, - { - "label": "principalToken", - "offset": 0, - "slot": "202", - "type": "t_contract(IERC20)7699", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:115" - }, - { - "label": "collateralToken", - "offset": 0, - "slot": "203", - "type": "t_contract(IERC20)7699", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:116" - }, - { - "label": "marketId", - "offset": 0, - "slot": "204", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:118" - }, - { - "label": "totalPrincipalTokensCommitted", - "offset": 0, - "slot": "205", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:121" - }, - { - "label": "totalPrincipalTokensWithdrawn", - "offset": 0, - "slot": "206", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:122" - }, - { - "label": "totalPrincipalTokensLended", - "offset": 0, - "slot": "207", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:124" - }, - { - "label": "totalPrincipalTokensRepaid", - "offset": 0, - "slot": "208", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:125" - }, - { - "label": "excessivePrincipalTokensRepaid", - "offset": 0, - "slot": "209", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:126" - }, - { - "label": "totalInterestCollected", - "offset": 0, - "slot": "210", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:128" - }, - { - "label": "liquidityThresholdPercent", - "offset": 0, - "slot": "211", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:130" - }, - { - "label": "collateralRatio", - "offset": 2, - "slot": "211", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:131" - }, - { - "label": "maxLoanDuration", - "offset": 4, - "slot": "211", - "type": "t_uint32", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:133" - }, - { - "label": "interestRateLowerBound", - "offset": 8, - "slot": "211", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:134" - }, - { - "label": "interestRateUpperBound", - "offset": 10, - "slot": "211", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:135" - }, - { - "label": "activeBids", - "offset": 0, - "slot": "212", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:143" - }, - { - "label": "activeBidsAmountDueRemaining", - "offset": 0, - "slot": "213", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:144" - }, - { - "label": "tokenDifferenceFromLiquidations", - "offset": 0, - "slot": "214", - "type": "t_int256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:146" - }, - { - "label": "firstDepositMade", - "offset": 0, - "slot": "215", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:148" - }, - { - "label": "withdrawDelayTimeSeconds", - "offset": 0, - "slot": "216", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:149" - }, - { - "label": "poolOracleRoutes", - "offset": 0, - "slot": "217", - "type": "t_array(t_struct(PoolRouteConfig)38316_storage)dyn_storage", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:151" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "offset": 0, - "slot": "218", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:154" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "219", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Smart", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol:157" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_struct(PoolRouteConfig)38316_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_contract(IERC20)7699": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_contract(LenderCommitmentGroupShares)26509": { - "label": "contract LenderCommitmentGroupShares", - "numberOfBytes": "20" - }, - "t_int256": { - "label": "int256", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_struct(PoolRouteConfig)38316_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_uint16": { - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "ac55a82a3a1964fb2e10d092dd3e69466c34d3a4ca646180ce6d194ee489d709": { - "address": "0xfCd6Aa92D399260E8309800316CEc9b1F123621e", - "txHash": "0x9955d6835440fef394a59449ba5ea4a1947f998813dcf6185f929e1585b6e78d", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "lenderGroupBeacon", - "offset": 0, - "slot": "101", - "type": "t_address", - "contract": "LenderCommitmentGroupFactory", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol:29" - }, - { - "label": "deployedLenderGroupContracts", - "offset": 0, - "slot": "102", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupFactory", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol:32" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "c8d7b90093e71c94d09f4e272108089f270011c5e03a0bf523ee49820a9ed773": { - "address": "0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB", - "txHash": "0x7bee836c98049d64b4b6c932b64ce3e313be4b52d32fff7cd4f8202d4d9fa69f", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_protocolPaused", - "offset": 0, - "slot": "101", - "type": "t_bool", - "contract": "ProtocolPausingManager", - "src": "contracts/pausing/ProtocolPausingManager.sol:23" - }, - { - "label": "_liquidationsPaused", - "offset": 1, - "slot": "101", - "type": "t_bool", - "contract": "ProtocolPausingManager", - "src": "contracts/pausing/ProtocolPausingManager.sol:24" - }, - { - "label": "pauserRoleBearer", - "offset": 0, - "slot": "102", - "type": "t_mapping(t_address,t_bool)", - "contract": "ProtocolPausingManager", - "src": "contracts/pausing/ProtocolPausingManager.sol:26" - }, - { - "label": "lastPausedAt", - "offset": 0, - "slot": "103", - "type": "t_uint256", - "contract": "ProtocolPausingManager", - "src": "contracts/pausing/ProtocolPausingManager.sol:29" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "104", - "type": "t_uint256", - "contract": "ProtocolPausingManager", - "src": "contracts/pausing/ProtocolPausingManager.sol:30" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_mapping(t_address,t_bool)": { - "label": "mapping(address => bool)", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "80889dce3a01abff40361826aa8e12a56254a298b2db1bc457492a6524584da3": { - "address": "0x7292385522F11390B2A7dd4677528fFce03b80db", - "txHash": "0xcab681e0d56e82dc6a30cc90497c16393196ed350751d5b84233562176e84363", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" - }, - { - "label": "lenderAttestationSchemaId", - "offset": 0, - "slot": "1", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:52" - }, - { - "label": "markets", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint256,t_struct(Marketplace)29593_storage)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:54" - }, - { - "label": "__uriToId", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_bytes32,t_uint256)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:55" - }, - { - "label": "marketCount", - "offset": 0, - "slot": "4", - "type": "t_uint256", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:56" - }, - { - "label": "_attestingSchemaId", - "offset": 0, - "slot": "5", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:57" - }, - { - "label": "borrowerAttestationSchemaId", - "offset": 0, - "slot": "6", - "type": "t_bytes32", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:58" - }, - { - "label": "version", - "offset": 0, - "slot": "7", - "type": "t_uint256", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:60" - }, - { - "label": "marketIsClosed", - "offset": 0, - "slot": "8", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:62" - }, - { - "label": "tellerAS", - "offset": 0, - "slot": "9", - "type": "t_contract(TellerAS)15929", - "contract": "MarketRegistry", - "src": "contracts/MarketRegistry.sol:64" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_contract(TellerAS)15929": { - "label": "contract TellerAS", - "numberOfBytes": "20" - }, - "t_enum(PaymentCycleType)42637": { - "label": "enum PaymentCycleType", - "members": [ - "Seconds", - "Monthly" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentType)42634": { - "label": "enum PaymentType", - "members": [ - "EMI", - "Bullet" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_bytes32)": { - "label": "mapping(address => bytes32)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Marketplace)29593_storage)": { - "label": "mapping(uint256 => struct MarketRegistry.Marketplace)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)13384_storage": { - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)13069_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Marketplace)29593_storage": { - "label": "struct MarketRegistry.Marketplace", - "members": [ - { - "label": "owner", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "metadataURI", - "type": "t_string_storage", - "offset": 0, - "slot": "1" - }, - { - "label": "marketplaceFeePercent", - "type": "t_uint16", - "offset": 0, - "slot": "2" - }, - { - "label": "lenderAttestationRequired", - "type": "t_bool", - "offset": 2, - "slot": "2" - }, - { - "label": "verifiedLendersForMarket", - "type": "t_struct(AddressSet)13384_storage", - "offset": 0, - "slot": "3" - }, - { - "label": "lenderAttestationIds", - "type": "t_mapping(t_address,t_bytes32)", - "offset": 0, - "slot": "5" - }, - { - "label": "paymentCycleDuration", - "type": "t_uint32", - "offset": 0, - "slot": "6" - }, - { - "label": "paymentDefaultDuration", - "type": "t_uint32", - "offset": 4, - "slot": "6" - }, - { - "label": "bidExpirationTime", - "type": "t_uint32", - "offset": 8, - "slot": "6" - }, - { - "label": "borrowerAttestationRequired", - "type": "t_bool", - "offset": 12, - "slot": "6" - }, - { - "label": "verifiedBorrowersForMarket", - "type": "t_struct(AddressSet)13384_storage", - "offset": 0, - "slot": "7" - }, - { - "label": "borrowerAttestationIds", - "type": "t_mapping(t_address,t_bytes32)", - "offset": 0, - "slot": "9" - }, - { - "label": "feeRecipient", - "type": "t_address", - "offset": 0, - "slot": "10" - }, - { - "label": "paymentType", - "type": "t_enum(PaymentType)42634", - "offset": 20, - "slot": "10" - }, - { - "label": "paymentCycleType", - "type": "t_enum(PaymentCycleType)42637", - "offset": 21, - "slot": "10" - } - ], - "numberOfBytes": "352" - }, - "t_struct(Set)13069_storage": { - "label": "struct EnumerableSet.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": {} - } - }, - "44335dcc5935759330e758578dfefa04d92e72a3bfb01cc2e34b8634dee6e672": { - "address": "0x48EE9c344d5C6d202F4b3225A694957a3412008d", - "txHash": "0x046e274123377efb8bd8d37bda9f161357d0aba8d077f7cbe759152105d8cc8c", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_protocolFee", - "offset": 0, - "slot": "101", - "type": "t_uint16", - "contract": "ProtocolFee", - "src": "contracts/ProtocolFee.sol:8" - }, - { - "label": "__paused", - "offset": 2, - "slot": "101", - "type": "t_bool", - "contract": "HasProtocolPausingManager", - "src": "contracts/pausing/HasProtocolPausingManager.sol:18" - }, - { - "label": "_protocolPausingManager", - "offset": 3, - "slot": "101", - "type": "t_address", - "contract": "HasProtocolPausingManager", - "src": "contracts/pausing/HasProtocolPausingManager.sol:20" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "HasProtocolPausingManager", - "src": "contracts/pausing/HasProtocolPausingManager.sol:57" - }, - { - "label": "bidId", - "offset": 0, - "slot": "151", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:92" - }, - { - "label": "bids", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_uint256,t_struct(Bid)35906_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:95" - }, - { - "label": "borrowerBids", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_address,t_array(t_uint256)dyn_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:98" - }, - { - "label": "__lenderVolumeFilled", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_address,t_uint256)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:101" - }, - { - "label": "__totalVolumeFilled", - "offset": 0, - "slot": "155", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:104" - }, - { - "label": "__lendingTokensSet", - "offset": 0, - "slot": "156", - "type": "t_struct(AddressSet)13384_storage", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:107" - }, - { - "label": "marketRegistry", - "offset": 0, - "slot": "158", - "type": "t_contract(IMarketRegistry)37778", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:109" - }, - { - "label": "reputationManager", - "offset": 0, - "slot": "159", - "type": "t_contract(IReputationManager)37873", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:110" - }, - { - "label": "_borrowerBidsActive", - "offset": 0, - "slot": "160", - "type": "t_mapping(t_address,t_struct(UintSet)13541_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:113" - }, - { - "label": "bidDefaultDuration", - "offset": 0, - "slot": "161", - "type": "t_mapping(t_uint256,t_uint32)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:115" - }, - { - "label": "bidExpirationTime", - "offset": 0, - "slot": "162", - "type": "t_mapping(t_uint256,t_uint32)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:116" - }, - { - "label": "lenderVolumeFilled", - "offset": 0, - "slot": "163", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:120" - }, - { - "label": "totalVolumeFilled", - "offset": 0, - "slot": "164", - "type": "t_mapping(t_address,t_uint256)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:124" - }, - { - "label": "version", - "offset": 0, - "slot": "165", - "type": "t_uint256", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:126" - }, - { - "label": "uris", - "offset": 0, - "slot": "166", - "type": "t_mapping(t_uint256,t_string_storage)", - "contract": "TellerV2Storage_G0", - "src": "contracts/TellerV2Storage.sol:130" - }, - { - "label": "_trustedMarketForwarders", - "offset": 0, - "slot": "167", - "type": "t_mapping(t_uint256,t_address)", - "contract": "TellerV2Storage_G1", - "src": "contracts/TellerV2Storage.sol:135" - }, - { - "label": "_approvedForwarderSenders", - "offset": 0, - "slot": "168", - "type": "t_mapping(t_address,t_struct(AddressSet)13384_storage)", - "contract": "TellerV2Storage_G1", - "src": "contracts/TellerV2Storage.sol:137" - }, - { - "label": "lenderCommitmentForwarder", - "offset": 0, - "slot": "169", - "type": "t_address", - "contract": "TellerV2Storage_G2", - "src": "contracts/TellerV2Storage.sol:142" - }, - { - "label": "collateralManager", - "offset": 0, - "slot": "170", - "type": "t_contract(ICollateralManager)36735", - "contract": "TellerV2Storage_G3", - "src": "contracts/TellerV2Storage.sol:146" - }, - { - "label": "lenderManager", - "offset": 0, - "slot": "171", - "type": "t_contract(ILenderManager)37507", - "contract": "TellerV2Storage_G4", - "src": "contracts/TellerV2Storage.sol:151" - }, - { - "label": "bidPaymentCycleType", - "offset": 0, - "slot": "172", - "type": "t_mapping(t_uint256,t_enum(PaymentCycleType)42637)", - "contract": "TellerV2Storage_G4", - "src": "contracts/TellerV2Storage.sol:153" - }, - { - "label": "escrowVault", - "offset": 0, - "slot": "173", - "type": "t_contract(IEscrowVault)37073", - "contract": "TellerV2Storage_G5", - "src": "contracts/TellerV2Storage.sol:158" - }, - { - "label": "repaymentListenerForBid", - "offset": 0, - "slot": "174", - "type": "t_mapping(t_uint256,t_address)", - "contract": "TellerV2Storage_G6", - "src": "contracts/TellerV2Storage.sol:162" - }, - { - "label": "__pauserRoleBearer", - "offset": 0, - "slot": "175", - "type": "t_mapping(t_address,t_bool)", - "contract": "TellerV2Storage_G7", - "src": "contracts/TellerV2Storage.sol:166" - }, - { - "label": "__liquidationsPaused", - "offset": 0, - "slot": "176", - "type": "t_bool", - "contract": "TellerV2Storage_G7", - "src": "contracts/TellerV2Storage.sol:167" - }, - { - "label": "protocolFeeRecipient", - "offset": 1, - "slot": "176", - "type": "t_address", - "contract": "TellerV2Storage_G8", - "src": "contracts/TellerV2Storage.sol:171" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "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_array(t_uint256)dyn_storage": { - "label": "uint256[]", - "numberOfBytes": "32" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_contract(ICollateralManager)36735": { - "label": "contract ICollateralManager", - "numberOfBytes": "20" - }, - "t_contract(IERC20)7699": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_contract(IEscrowVault)37073": { - "label": "contract IEscrowVault", - "numberOfBytes": "20" - }, - "t_contract(ILenderManager)37507": { - "label": "contract ILenderManager", - "numberOfBytes": "20" - }, - "t_contract(IMarketRegistry)37778": { - "label": "contract IMarketRegistry", - "numberOfBytes": "20" - }, - "t_contract(IReputationManager)37873": { - "label": "contract IReputationManager", - "numberOfBytes": "20" - }, - "t_enum(BidState)35878": { - "label": "enum BidState", - "members": [ - "NONEXISTENT", - "PENDING", - "CANCELLED", - "ACCEPTED", - "PAID", - "LIQUIDATED", - "CLOSED" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentCycleType)42637": { - "label": "enum PaymentCycleType", - "members": [ - "Seconds", - "Monthly" - ], - "numberOfBytes": "1" - }, - "t_enum(PaymentType)42634": { - "label": "enum PaymentType", - "members": [ - "EMI", - "Bullet" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_array(t_uint256)dyn_storage)": { - "label": "mapping(address => uint256[])", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_bool)": { - "label": "mapping(address => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_struct(AddressSet)13384_storage)": { - "label": "mapping(address => struct EnumerableSet.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_struct(UintSet)13541_storage)": { - "label": "mapping(address => struct EnumerableSet.UintSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_address)": { - "label": "mapping(uint256 => address)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_enum(PaymentCycleType)42637)": { - "label": "mapping(uint256 => enum PaymentCycleType)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_string_storage)": { - "label": "mapping(uint256 => string)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Bid)35906_storage)": { - "label": "mapping(uint256 => struct Bid)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint32)": { - "label": "mapping(uint256 => uint32)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)13384_storage": { - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)13069_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Bid)35906_storage": { - "label": "struct Bid", - "members": [ - { - "label": "borrower", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "receiver", - "type": "t_address", - "offset": 0, - "slot": "1" - }, - { - "label": "lender", - "type": "t_address", - "offset": 0, - "slot": "2" - }, - { - "label": "marketplaceId", - "type": "t_uint256", - "offset": 0, - "slot": "3" - }, - { - "label": "_metadataURI", - "type": "t_bytes32", - "offset": 0, - "slot": "4" - }, - { - "label": "loanDetails", - "type": "t_struct(LoanDetails)35923_storage", - "offset": 0, - "slot": "5" - }, - { - "label": "terms", - "type": "t_struct(Terms)35930_storage", - "offset": 0, - "slot": "10" - }, - { - "label": "state", - "type": "t_enum(BidState)35878", - "offset": 0, - "slot": "12" - }, - { - "label": "paymentType", - "type": "t_enum(PaymentType)42634", - "offset": 1, - "slot": "12" - } - ], - "numberOfBytes": "416" - }, - "t_struct(LoanDetails)35923_storage": { - "label": "struct LoanDetails", - "members": [ - { - "label": "lendingToken", - "type": "t_contract(IERC20)7699", - "offset": 0, - "slot": "0" - }, - { - "label": "principal", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "totalRepaid", - "type": "t_struct(Payment)35883_storage", - "offset": 0, - "slot": "2" - }, - { - "label": "timestamp", - "type": "t_uint32", - "offset": 0, - "slot": "4" - }, - { - "label": "acceptedTimestamp", - "type": "t_uint32", - "offset": 4, - "slot": "4" - }, - { - "label": "lastRepaidTimestamp", - "type": "t_uint32", - "offset": 8, - "slot": "4" - }, - { - "label": "loanDuration", - "type": "t_uint32", - "offset": 12, - "slot": "4" - } - ], - "numberOfBytes": "160" - }, - "t_struct(Payment)35883_storage": { - "label": "struct Payment", - "members": [ - { - "label": "principal", - "type": "t_uint256", - "offset": 0, - "slot": "0" - }, - { - "label": "interest", - "type": "t_uint256", - "offset": 0, - "slot": "1" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Set)13069_storage": { - "label": "struct EnumerableSet.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_struct(Terms)35930_storage": { - "label": "struct Terms", - "members": [ - { - "label": "paymentCycleAmount", - "type": "t_uint256", - "offset": 0, - "slot": "0" - }, - { - "label": "paymentCycle", - "type": "t_uint32", - "offset": 0, - "slot": "1" - }, - { - "label": "APR", - "type": "t_uint16", - "offset": 4, - "slot": "1" - } - ], - "numberOfBytes": "64" - }, - "t_struct(UintSet)13541_storage": { - "label": "struct EnumerableSet.UintSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)13069_storage", - "offset": 0, - "slot": "0" - } - ], - "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": {} - } - }, - "09309c8f0bdf37dae4bf58a96b9b4e057ebfc0f14707ad34e58a9f84fa6fe212": { - "address": "0xb7695470E9c8d6E84F4786C240960B7822106b63", - "txHash": "0xb4403f8fd35928b35b408cc87ec1d630440df31f25e3e9226699c70ab00f0136", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "tellerV2", - "offset": 0, - "slot": "101", - "type": "t_contract(ITellerV2)38227", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:24" - }, - { - "label": "collateralEscrowBeacon", - "offset": 0, - "slot": "102", - "type": "t_address", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:25" - }, - { - "label": "_escrows", - "offset": 0, - "slot": "103", - "type": "t_mapping(t_uint256,t_address)", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:28" - }, - { - "label": "_bidCollaterals", - "offset": 0, - "slot": "104", - "type": "t_mapping(t_uint256,t_struct(CollateralInfo)13720_storage)", - "contract": "CollateralManager", - "src": "contracts/CollateralManager.sol:30" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "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_contract(ITellerV2)38227": { - "label": "contract ITellerV2", - "numberOfBytes": "20" - }, - "t_enum(CollateralType)39921": { - "label": "enum CollateralType", - "members": [ - "ERC20", - "ERC721", - "ERC1155" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_struct(Collateral)39931_storage)": { - "label": "mapping(address => struct Collateral)", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_address)": { - "label": "mapping(uint256 => address)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(CollateralInfo)13720_storage)": { - "label": "mapping(uint256 => struct CollateralManager.CollateralInfo)", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)5209_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)4894_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Collateral)39931_storage": { - "label": "struct Collateral", - "members": [ - { - "label": "_collateralType", - "type": "t_enum(CollateralType)39921", - "offset": 0, - "slot": "0" - }, - { - "label": "_amount", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "_tokenId", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "_collateralAddress", - "type": "t_address", - "offset": 0, - "slot": "3" - } - ], - "numberOfBytes": "128" - }, - "t_struct(CollateralInfo)13720_storage": { - "label": "struct CollateralManager.CollateralInfo", - "members": [ - { - "label": "collateralAddresses", - "type": "t_struct(AddressSet)5209_storage", - "offset": 0, - "slot": "0" - }, - { - "label": "collateralInfo", - "type": "t_mapping(t_address,t_struct(Collateral)39931_storage)", - "offset": 0, - "slot": "2" - } - ], - "numberOfBytes": "96" - }, - "t_struct(Set)4894_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_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "ce39878ecd9200ccdebe2ced384987a3a016d16553069380ba583f8183124209": { - "address": "0x0AeeeD450EcCaFaA140222De43963B179B514540", - "txHash": "0xb9dc20d1ca880c95c74e8afd2a65c46c62be192c94032a56202c332f3c582b66", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "bidId", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "CollateralEscrowV1", - "src": "contracts/escrow/CollateralEscrowV1.sol:17" - }, - { - "label": "collateralBalances", - "offset": 0, - "slot": "102", - "type": "t_mapping(t_address,t_struct(Collateral)39931_storage)", - "contract": "CollateralEscrowV1", - "src": "contracts/escrow/CollateralEscrowV1.sol:19" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_enum(CollateralType)39921": { - "label": "enum CollateralType", - "members": [ - "ERC20", - "ERC721", - "ERC1155" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_struct(Collateral)39931_storage)": { - "label": "mapping(address => struct Collateral)", - "numberOfBytes": "32" - }, - "t_struct(Collateral)39931_storage": { - "label": "struct Collateral", - "members": [ - { - "label": "_collateralType", - "type": "t_enum(CollateralType)39921", - "offset": 0, - "slot": "0" - }, - { - "label": "_amount", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "_tokenId", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "_collateralAddress", - "type": "t_address", - "offset": 0, - "slot": "3" - } - ], - "numberOfBytes": "128" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "d4973d15578a28819bc5862bd8be29bf04edb45def32e5edc48c589eef39471c": { - "address": "0x6578dA23E0A7D9d13d4B32aA1cF310760218eebf", - "txHash": "0x3d8ad710aac4e914f59ce8f162f5e94b2cabdd9f18e12c6452498b6e5d06c49a", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "b8b650939092afbdd12b14adbe177681ff76dc663bebd532791e98aec6bc3dc9": { - "address": "0xB8Ab54664ed8F9f298778E8aEAA748A5818cb8C8", - "txHash": "0x4ee923722977d5fa1b994f27ac41213c1d739a70cadfbd876ff74924103c2ab4", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "b9185bdb1554d2e98ae3bef41109124bb073b88689c465be4d48c503e4de2928": { - "address": "0x912C09846b46a746DcbF5Ff2aDDA609A73ef6e9A", - "txHash": "0x2396b74d916fb32e37334fd4aa57073e0a4a7e7c059a18cd36a4949d8b62f607", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "4a2b6887b9d33e54577aaccc4a1fc0b8b3a5bb210da32d0dbbf622447a1dca7e": { - "address": "0x26E2BD4F67136a7929DFE82BD6392633eb5610C2", - "txHash": "0x15e935a0b1022e130a2c05d8937d0f541c2662bc2af0139bd6ebbc236bf81451", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_status", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_balances", - "offset": 0, - "slot": "151", - "type": "t_mapping(t_address,t_uint256)", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" - }, - { - "label": "_allowances", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" - }, - { - "label": "_totalSupply", - "offset": 0, - "slot": "153", - "type": "t_uint256", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" - }, - { - "label": "_name", - "offset": 0, - "slot": "154", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" - }, - { - "label": "_symbol", - "offset": 0, - "slot": "155", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" - }, - { - "label": "__gap", - "offset": 0, - "slot": "156", - "type": "t_array(t_uint256)45_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" - }, - { - "label": "poolSharesLastTransferredAt", - "offset": 0, - "slot": "201", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)50_storage", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" - }, - { - "label": "principalToken", - "offset": 0, - "slot": "252", - "type": "t_contract(IERC20)8314", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:118" - }, - { - "label": "collateralToken", - "offset": 0, - "slot": "253", - "type": "t_contract(IERC20)8314", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:119" - }, - { - "label": "marketId", - "offset": 0, - "slot": "254", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:121" - }, - { - "label": "totalPrincipalTokensCommitted", - "offset": 0, - "slot": "255", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:124" - }, - { - "label": "totalPrincipalTokensWithdrawn", - "offset": 0, - "slot": "256", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:125" - }, - { - "label": "totalPrincipalTokensLended", - "offset": 0, - "slot": "257", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:127" - }, - { - "label": "totalPrincipalTokensRepaid", - "offset": 0, - "slot": "258", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:128" - }, - { - "label": "excessivePrincipalTokensRepaid", - "offset": 0, - "slot": "259", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:129" - }, - { - "label": "totalInterestCollected", - "offset": 0, - "slot": "260", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:131" - }, - { - "label": "liquidityThresholdPercent", - "offset": 0, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:133" - }, - { - "label": "collateralRatio", - "offset": 2, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:134" - }, - { - "label": "maxLoanDuration", - "offset": 4, - "slot": "261", - "type": "t_uint32", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:136" - }, - { - "label": "interestRateLowerBound", - "offset": 8, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:137" - }, - { - "label": "interestRateUpperBound", - "offset": 10, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:138" - }, - { - "label": "activeBids", - "offset": 0, - "slot": "262", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:146" - }, - { - "label": "activeBidsAmountDueRemaining", - "offset": 0, - "slot": "263", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:147" - }, - { - "label": "tokenDifferenceFromLiquidations", - "offset": 0, - "slot": "264", - "type": "t_int256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:149" - }, - { - "label": "firstDepositMade", - "offset": 0, - "slot": "265", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:151" - }, - { - "label": "withdrawDelayTimeSeconds", - "offset": 0, - "slot": "266", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:152" - }, - { - "label": "poolOracleRoutes", - "offset": 0, - "slot": "267", - "type": "t_array(t_struct(PoolRouteConfig)46253_storage)dyn_storage", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:154" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "offset": 0, - "slot": "268", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:157" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "269", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:160" - }, - { - "label": "paused", - "offset": 0, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:161" - }, - { - "label": "borrowingPaused", - "offset": 1, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:162" - }, - { - "label": "liquidationAuctionPaused", - "offset": 2, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:163" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_struct(PoolRouteConfig)46253_storage)dyn_storage": { - "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", - "numberOfBytes": "32" - }, - "t_array(t_uint256)45_storage": { - "label": "uint256[45]", - "numberOfBytes": "1440" - }, - "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_contract(IERC20)8314": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_int256": { - "label": "int256", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(PoolRouteConfig)46253_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_uint16": { - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "6f01541265576f4854242ff526c30b4e304ae07d7b0c03a7210326a561fea83e": { - "address": "0xC764a44Faa62dB04310e0c8eA8d56FDC411e3e31", - "txHash": "0x2ab6dd1b71a4cb37d5d250c5d79bdcea72675e0e74cc5b2831025e70b85ce5c6", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "lenderGroupBeacon", - "offset": 0, - "slot": "101", - "type": "t_address", - "contract": "LenderCommitmentGroupFactory_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:32" - }, - { - "label": "deployedLenderGroupContracts", - "offset": 0, - "slot": "102", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupFactory_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:36" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "d28f103516b18c192468c845128f88c37bf51eb6fb6c0830042c187d805a56e4": { - "address": "0xE9D02C0e0449A396A09A42fE03Ff06300C972Db5", - "txHash": "0x471525f0e3842796a3df64c89dc25ceae34e098ee1797a5f9f73c1bd6ec1c190", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, - "587d66a3444e8732bfb54daf05d3c8cba241511c0476f0f0ced73eb70831c7bf": { - "address": "0x5250005b25656449C9ac5F401eDfFD1cEe833883", - "txHash": "0x9b5080621bfcbb0b77703b13f1985585280af5b81d1dbde984887ddd71c03fff", - "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": "__gap", - "offset": 0, - "slot": "151", - "type": "t_array(t_uint256)50_storage", - "contract": "TellerV2MarketForwarder_G3", - "src": "contracts/TellerV2MarketForwarder_G3.sol:59" - }, - { - "label": "_paused", - "offset": 0, - "slot": "201", - "type": "t_bool", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)49_storage", - "contract": "PausableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" - }, - { - "label": "_status", - "offset": 0, - "slot": "251", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "252", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_owner", - "offset": 0, - "slot": "301", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "302", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "liquidationProtocolFeePercent", - "offset": 0, - "slot": "351", - "type": "t_uint256", - "contract": "SmartCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:88" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "352", - "type": "t_uint256", - "contract": "SmartCommitmentForwarder", - "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:89" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "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_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_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - }, - "allAddresses": [ - "0x5250005b25656449C9ac5F401eDfFD1cEe833883", - "0x48f4DDbc34A0DF3b5aC2B13Db4895fa980607aa9" - ] - }, - "3329a9b1fa7f8bd0cf56c7761c1a91a3e87780cd1a83d46df278ac9c26d3a4d0": { - "address": "0x6d1a1aA0bf7048C6dE655C375aBC1dD961102744", - "txHash": "0x560c6b89b504b7d7a03583695be630f54d4e5ccb0a522d5226bf849947e655f6", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_status", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_balances", - "offset": 0, - "slot": "151", - "type": "t_mapping(t_address,t_uint256)", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" - }, - { - "label": "_allowances", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" - }, - { - "label": "_totalSupply", - "offset": 0, - "slot": "153", - "type": "t_uint256", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" - }, - { - "label": "_name", - "offset": 0, - "slot": "154", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" - }, - { - "label": "_symbol", - "offset": 0, - "slot": "155", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" - }, - { - "label": "__gap", - "offset": 0, - "slot": "156", - "type": "t_array(t_uint256)45_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" - }, - { - "label": "poolSharesLastTransferredAt", - "offset": 0, - "slot": "201", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)50_storage", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" - }, - { - "label": "principalToken", - "offset": 0, - "slot": "252", - "type": "t_contract(IERC20)5023", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:118" - }, - { - "label": "collateralToken", - "offset": 0, - "slot": "253", - "type": "t_contract(IERC20)5023", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:119" - }, - { - "label": "marketId", - "offset": 0, - "slot": "254", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:121" - }, - { - "label": "totalPrincipalTokensCommitted", - "offset": 0, - "slot": "255", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:124" - }, - { - "label": "totalPrincipalTokensWithdrawn", - "offset": 0, - "slot": "256", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:125" - }, - { - "label": "totalPrincipalTokensLended", - "offset": 0, - "slot": "257", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:127" - }, - { - "label": "totalPrincipalTokensRepaid", - "offset": 0, - "slot": "258", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:128" - }, - { - "label": "excessivePrincipalTokensRepaid", - "offset": 0, - "slot": "259", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:129" - }, - { - "label": "totalInterestCollected", - "offset": 0, - "slot": "260", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:131" - }, - { - "label": "liquidityThresholdPercent", - "offset": 0, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:133" - }, - { - "label": "collateralRatio", - "offset": 2, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:134" - }, - { - "label": "maxLoanDuration", - "offset": 4, - "slot": "261", - "type": "t_uint32", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:136" - }, - { - "label": "interestRateLowerBound", - "offset": 8, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:137" - }, - { - "label": "interestRateUpperBound", - "offset": 10, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:138" - }, - { - "label": "activeBids", - "offset": 0, - "slot": "262", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:146" - }, - { - "label": "activeBidsAmountDueRemaining", - "offset": 0, - "slot": "263", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:147" - }, - { - "label": "tokenDifferenceFromLiquidations", - "offset": 0, - "slot": "264", - "type": "t_int256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:149" - }, - { - "label": "firstDepositMade_deprecated", - "offset": 0, - "slot": "265", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:151" - }, - { - "label": "withdrawDelayTimeSeconds", - "offset": 0, - "slot": "266", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:152" - }, - { - "label": "poolOracleRoutes", - "offset": 0, - "slot": "267", - "type": "t_array(t_struct(PoolRouteConfig)15693_storage)dyn_storage", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:154" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "offset": 0, - "slot": "268", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:157" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "269", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:160" - }, - { - "label": "paused", - "offset": 0, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:161" - }, - { - "label": "borrowingPaused", - "offset": 1, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:162" - }, - { - "label": "liquidationAuctionPaused", - "offset": 2, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:163" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_struct(PoolRouteConfig)15693_storage)dyn_storage": { - "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", - "numberOfBytes": "32" - }, - "t_array(t_uint256)45_storage": { - "label": "uint256[45]", - "numberOfBytes": "1440" - }, - "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_contract(IERC20)5023": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_int256": { - "label": "int256", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(PoolRouteConfig)15693_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_uint16": { - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "0e269c8bddf39ae58e98da7c876861a97c996b38d2dcdc057c90b9f4d98b49ef": { - "address": "0xd177f4b8e348B4C56c2aC8E03b58E41b79351a7f", - "txHash": "0x3591eb644fc68d027682a324ddc056cc23368a95acd15f0c89c5da2474f3dadb", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "_owner", - "offset": 0, - "slot": "51", - "type": "t_address", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" - }, - { - "label": "__gap", - "offset": 0, - "slot": "52", - "type": "t_array(t_uint256)49_storage", - "contract": "OwnableUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" - }, - { - "label": "_status", - "offset": 0, - "slot": "101", - "type": "t_uint256", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" - }, - { - "label": "__gap", - "offset": 0, - "slot": "102", - "type": "t_array(t_uint256)49_storage", - "contract": "ReentrancyGuardUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" - }, - { - "label": "_balances", - "offset": 0, - "slot": "151", - "type": "t_mapping(t_address,t_uint256)", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" - }, - { - "label": "_allowances", - "offset": 0, - "slot": "152", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" - }, - { - "label": "_totalSupply", - "offset": 0, - "slot": "153", - "type": "t_uint256", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" - }, - { - "label": "_name", - "offset": 0, - "slot": "154", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" - }, - { - "label": "_symbol", - "offset": 0, - "slot": "155", - "type": "t_string_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" - }, - { - "label": "__gap", - "offset": 0, - "slot": "156", - "type": "t_array(t_uint256)45_storage", - "contract": "ERC20Upgradeable", - "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" - }, - { - "label": "poolSharesLastTransferredAt", - "offset": 0, - "slot": "201", - "type": "t_mapping(t_address,t_uint256)", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" - }, - { - "label": "__gap", - "offset": 0, - "slot": "202", - "type": "t_array(t_uint256)50_storage", - "contract": "LenderCommitmentGroupSharesIntegrated", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" - }, - { - "label": "principalToken", - "offset": 0, - "slot": "252", - "type": "t_contract(IERC20)8314", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:119" - }, - { - "label": "collateralToken", - "offset": 0, - "slot": "253", - "type": "t_contract(IERC20)8314", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:120" - }, - { - "label": "marketId", - "offset": 0, - "slot": "254", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:122" - }, - { - "label": "totalPrincipalTokensCommitted", - "offset": 0, - "slot": "255", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:125" - }, - { - "label": "totalPrincipalTokensWithdrawn", - "offset": 0, - "slot": "256", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:126" - }, - { - "label": "totalPrincipalTokensLended", - "offset": 0, - "slot": "257", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:128" - }, - { - "label": "totalPrincipalTokensRepaid", - "offset": 0, - "slot": "258", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:129" - }, - { - "label": "excessivePrincipalTokensRepaid", - "offset": 0, - "slot": "259", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:130" - }, - { - "label": "totalInterestCollected", - "offset": 0, - "slot": "260", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:132" - }, - { - "label": "liquidityThresholdPercent", - "offset": 0, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:134" - }, - { - "label": "collateralRatio", - "offset": 2, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:135" - }, - { - "label": "maxLoanDuration", - "offset": 4, - "slot": "261", - "type": "t_uint32", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:137" - }, - { - "label": "interestRateLowerBound", - "offset": 8, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:138" - }, - { - "label": "interestRateUpperBound", - "offset": 10, - "slot": "261", - "type": "t_uint16", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:139" - }, - { - "label": "activeBids", - "offset": 0, - "slot": "262", - "type": "t_mapping(t_uint256,t_bool)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:147" - }, - { - "label": "activeBidsAmountDueRemaining", - "offset": 0, - "slot": "263", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:148" - }, - { - "label": "tokenDifferenceFromLiquidations", - "offset": 0, - "slot": "264", - "type": "t_int256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:150" - }, - { - "label": "firstDepositMade_deprecated", - "offset": 0, - "slot": "265", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:152" - }, - { - "label": "withdrawDelayTimeSeconds", - "offset": 0, - "slot": "266", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:153" - }, - { - "label": "poolOracleRoutes", - "offset": 0, - "slot": "267", - "type": "t_array(t_struct(PoolRouteConfig)47332_storage)dyn_storage", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:155" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "offset": 0, - "slot": "268", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:158" - }, - { - "label": "lastUnpausedAt", - "offset": 0, - "slot": "269", - "type": "t_uint256", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:161" - }, - { - "label": "paused", - "offset": 0, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:162" - }, - { - "label": "borrowingPaused", - "offset": 1, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:163" - }, - { - "label": "liquidationAuctionPaused", - "offset": 2, - "slot": "270", - "type": "t_bool", - "contract": "LenderCommitmentGroup_Pool_V2", - "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:164" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_struct(PoolRouteConfig)47332_storage)dyn_storage": { - "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", - "numberOfBytes": "32" - }, - "t_array(t_uint256)45_storage": { - "label": "uint256[45]", - "numberOfBytes": "1440" - }, - "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_contract(IERC20)8314": { - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_int256": { - "label": "int256", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_uint256)": { - "label": "mapping(address => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_bool)": { - "label": "mapping(uint256 => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_string_storage": { - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(PoolRouteConfig)47332_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_uint16": { - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "e3e27a58e9bdb60b1d19cdf6040224f6a4c4ab2dea84c085874384030d7936b7": { - "address": "0x55Ef5d3700eEC151d4Feff74214E7C90daBDE12B", - "txHash": "0xed76659c58a3645923836e7076b6ebd96dac0a849ca7dc858892bee797790b6e", - "layout": { - "solcVersion": "0.8.11", - "storage": [], - "types": {}, - "namespaces": {} - } - }, "c0994cac2d4f19b7af67e484cb25e90e135c727a1315840028c31cd9f47b8a50": { - "address": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", - "txHash": "0x702ed8bca3a1a7ea5111d2a308472cf540e716c2c70ac255f80454142946f959", + "address": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f", + "txHash": "0x17c6a9c1410ad28a161f76dd0bff8adb1113650bb66e1095fd2238b2d6c444ff", "layout": { "solcVersion": "0.8.24", "storage": [ diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts index 3d9f89d5c..ab8cb1687 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts @@ -46,7 +46,8 @@ const deployFn: DeployFunction = async (hre) => { smartCommitmentForwarderAddress, // priceAdapterAddress, ], - + redeployImplementation: 'always', + } ) diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts index 6f6f43b3f..54344279c 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts @@ -24,6 +24,8 @@ const deployFn: DeployFunction = async (hre) => { initArgs: [ LenderGroupsBeaconAddress ], + + } ) diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index b54efb620..91732b330 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,5 +42,7 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216 + "timelock-controller:update-delay-7200": 1757524216, + "lender-commitment-group-beacon-v3:deploy": 1763508918, + "lender-commitment-group-factory-v3:deploy": 1763509018 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json new file mode 100644 index 000000000..7aacde2f2 --- /dev/null +++ b/packages/contracts/deployments/base/FixedPointQ96.json @@ -0,0 +1,134 @@ +{ + "address": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "divideFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "q96Value", + "type": "uint256" + } + ], + "name": "fromFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "multiplyFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "numerator", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "denominator", + "type": "uint256" + } + ], + "name": "toFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + } + ], + "transactionHash": "0xde56421f241a4e54892c66dd1a53791650fda5bdfceddbf1a6af0f7435674862", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", + "transactionIndex": 293, + "gasUsed": "141837", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x3058c34fc3900b8e1d6c8af658ee9521c419354d8965f457c3ac48348fae9506", + "transactionHash": "0xde56421f241a4e54892c66dd1a53791650fda5bdfceddbf1a6af0f7435674862", + "logs": [], + "blockNumber": 38359836, + "cumulativeGasUsed": "32775643", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", + "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "devdoc": { + "kind": "dev", + "methods": {}, + "title": "FixedPoint96", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json new file mode 100644 index 000000000..056a19961 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json @@ -0,0 +1,1893 @@ +{ + "address": "0xfdC723Aa9874530470DA36cc0791b7DC1201a6ec", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_WITHDRAW_DELAY_TIME", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "firstDepositMade", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapter" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceAdapter", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceRouteHash", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_seconds" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0xF579ba9Ce33E392134Fd4a1A9D7D9d792eAF0B2b" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json new file mode 100644 index 000000000..6f0dfa35c --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json @@ -0,0 +1,218 @@ +{ + "address": "0x98eEbd694eE24935615BF18bA1ae75B2E486487f", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0xa8d2d589773b0db38e02cc7d27810432a440af30f9aaee53259319050b1f748a", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json new file mode 100644 index 000000000..23b2c594a --- /dev/null +++ b/packages/contracts/deployments/base/PriceAdapterAerodrome.json @@ -0,0 +1,239 @@ +{ + "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xda4bfa6b47ea07a051970fc4119cd23498e052b7f05d25e8026068d7c3df42f6", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", + "transactionIndex": 252, + "gasUsed": "993855", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xda11f9a6cf3a208e2079a20da271ed5ff66edc355e7d9c3155d16dbe850901c8", + "transactionHash": "0xda4bfa6b47ea07a051970fc4119cd23498e052b7f05d25e8026068d7c3df42f6", + "logs": [], + "blockNumber": 38359843, + "cumulativeGasUsed": "49442662", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b815260048101879052602481018290529091507398c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac7190637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 76889, + "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file From a430688aac754dcecc0ac259f94e763d0d51705c Mon Sep 17 00:00:00 2001 From: andy Date: Tue, 18 Nov 2025 18:38:20 -0500 Subject: [PATCH 29/46] improve deploy scripts --- .../contracts/deploy/pricing/price_adapter_aerodrome.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 68c03d447..a013c81cc 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -14,6 +14,13 @@ const deployFn: DeployFunction = async (hre) => { hre.log('FixedPointQ96 library deployed at:' ) hre.log( FixedPointQ96.address) + + + // need to add a delay , wait here ! + await tx.wait(1) // wait one block + + + // Deploy PriceAdapterAerodrome with linked library const PriceAdapterAerodrome = await hre.deployments.deploy('PriceAdapterAerodrome', { from: deployer, From 369aad3e36bb3f67730e33122e44d794ccaa89c5 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 20 Nov 2025 14:23:25 -0500 Subject: [PATCH 30/46] update factory v3 --- .../LenderCommitmentGroup_Factory_V3.sol | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol index 6a9a584db..58eadde0f 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol @@ -58,13 +58,15 @@ contract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable { * @dev The function initializes the deployed contract and optionally adds an initial principal amount. * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract. * @param _commitmentGroupConfig Configuration parameters for the lender commitment group. - * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library. + * @param _priceAdapterAddress Address for the pool price adapter + * @param _priceAdapterRoute Encoded roue for the price adapter * @return newGroupContract_ Address of the newly deployed group contract. */ function deployLenderCommitmentGroupPool( uint256 _initialPrincipalAmount, ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig, - IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes + address _priceAdapterAddress, + bytes calldata _priceAdapterRoute ) external returns ( address ) { @@ -73,7 +75,8 @@ contract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable { abi.encodeWithSelector( ILenderCommitmentGroup_V3.initialize.selector, //this initializes _commitmentGroupConfig, - _poolOracleRoutes + _priceAdapterAddress, + _priceAdapterRoute ) ); @@ -85,7 +88,7 @@ contract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable { //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have . if (_initialPrincipalAmount > 0) { - _depositPrincipal( + _depositPrincipal( address(newGroupContract_), _initialPrincipalAmount, _commitmentGroupConfig.principalTokenAddress From 075daa83da91723fed98e06e3c1874eef9b14a9b Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 20 Nov 2025 14:28:32 -0500 Subject: [PATCH 31/46] reset base state --- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 -- .../base/LenderCommitmentGroupBeaconV3.json | 1893 ----------------- .../base/LenderCommitmentGroupFactory_V3.json | 218 -- .../base/PriceAdapterAerodrome.json | 239 --- 5 files changed, 1 insertion(+), 2487 deletions(-) delete mode 100644 packages/contracts/deployments/base/FixedPointQ96.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json delete mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index 91732b330..b54efb620 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,7 +42,5 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216, - "lender-commitment-group-beacon-v3:deploy": 1763508918, - "lender-commitment-group-factory-v3:deploy": 1763509018 + "timelock-controller:update-delay-7200": 1757524216 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json deleted file mode 100644 index 7aacde2f2..000000000 --- a/packages/contracts/deployments/base/FixedPointQ96.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "address": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", - "abi": [ - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "divideFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "q96Value", - "type": "uint256" - } - ], - "name": "fromFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "multiplyFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "numerator", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "denominator", - "type": "uint256" - } - ], - "name": "toFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - } - ], - "transactionHash": "0xde56421f241a4e54892c66dd1a53791650fda5bdfceddbf1a6af0f7435674862", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71", - "transactionIndex": 293, - "gasUsed": "141837", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x3058c34fc3900b8e1d6c8af658ee9521c419354d8965f457c3ac48348fae9506", - "transactionHash": "0xde56421f241a4e54892c66dd1a53791650fda5bdfceddbf1a6af0f7435674862", - "logs": [], - "blockNumber": 38359836, - "cumulativeGasUsed": "32775643", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", - "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "devdoc": { - "kind": "dev", - "methods": {}, - "title": "FixedPoint96", - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", - "version": 1 - }, - "storageLayout": { - "storage": [], - "types": null - } -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json deleted file mode 100644 index 056a19961..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json +++ /dev/null @@ -1,1893 +0,0 @@ -{ - "address": "0xfdC723Aa9874530470DA36cc0791b7DC1201a6ec", - "abi": [ - { - "type": "constructor", - "stateMutability": "undefined", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_tellerV2" - }, - { - "type": "address", - "name": "_smartCommitmentForwarder" - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Approval", - "inputs": [ - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "address", - "name": "spender", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "BorrowerAcceptedFunds", - "inputs": [ - { - "type": "address", - "name": "borrower", - "indexed": true - }, - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "collateralAmount", - "indexed": false - }, - { - "type": "uint32", - "name": "loanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRate", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "DefaultedLoanLiquidated", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "liquidator", - "indexed": true - }, - { - "type": "uint256", - "name": "amountDue", - "indexed": false - }, - { - "type": "int256", - "name": "tokenAmountDifference", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Deposit", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "LoanRepaid", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "repayer", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "interestAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "totalPrincipalRepaid", - "indexed": false - }, - { - "type": "uint256", - "name": "totalInterestCollected", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Paused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PoolInitialized", - "inputs": [ - { - "type": "address", - "name": "principalTokenAddress", - "indexed": true - }, - { - "type": "address", - "name": "collateralTokenAddress", - "indexed": true - }, - { - "type": "uint256", - "name": "marketId", - "indexed": false - }, - { - "type": "uint32", - "name": "maxLoanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateLowerBound", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateUpperBound", - "indexed": false - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent", - "indexed": false - }, - { - "type": "uint16", - "name": "loanToValuePercent", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "SharesLastTransferredAt", - "inputs": [ - { - "type": "address", - "name": "recipient", - "indexed": true - }, - { - "type": "uint256", - "name": "transferredAt", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Transfer", - "inputs": [ - { - "type": "address", - "name": "from", - "indexed": true - }, - { - "type": "address", - "name": "to", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Unpaused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Withdraw", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "receiver", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "WithdrawFromEscrow", - "inputs": [ - { - "type": "uint256", - "name": "amount", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "EXCHANGE_RATE_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MAX_WITHDRAW_DELAY_TIME", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MIN_TWAP_INTERVAL", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "ORACLE_MANAGER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "SMART_COMMITMENT_FORWARDER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "TELLER_V2", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "UNISWAP_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "acceptFundsForAcceptBid", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_borrower" - }, - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "uint256", - "name": "_principalAmount" - }, - { - "type": "uint256", - "name": "_collateralAmount" - }, - { - "type": "address", - "name": "_collateralTokenAddress" - }, - { - "type": "uint256", - "name": "_collateralTokenId" - }, - { - "type": "uint32", - "name": "_loanDuration" - }, - { - "type": "uint16", - "name": "_interestRate" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "activeBids", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "activeBidsAmountDueRemaining", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "allowance", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - }, - { - "type": "address", - "name": "spender" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "approve", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "asset", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "assetTokenAddress" - } - ] - }, - { - "type": "function", - "name": "balanceOf", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "account" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "borrowingPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralRequiredToBorrowPrincipal", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "collateralTokensAmountToMatchValue" - } - ] - }, - { - "type": "function", - "name": "collateralRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "collateralToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToShares", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decimals", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decreaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "subtractedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deposit", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "excessivePrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "firstDepositMade", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenType", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getLastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMarketId", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMaxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinInterestRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "amountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amountOwed" - }, - { - "type": "uint256", - "name": "_loanDefaultedTimestamp" - } - ], - "outputs": [ - { - "type": "int256", - "name": "amountDifference_" - } - ] - }, - { - "type": "function", - "name": "getPoolUtilizationRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "activeLoansAmountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalAmountAvailableToBorrow", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getSharesLastTransferredAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getTokenDifferenceFromLiquidations", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "int256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "increaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "addedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "address", - "name": "_priceAdapter" - }, - { - "type": "bytes", - "name": "_priceAdapterRoute" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "interestRateLowerBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "interestRateUpperBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "lastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidateDefaultedLoanWithIncentive", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "int256", - "name": "_tokenAmountDifference" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "liquidationAuctionPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidityThresholdPercent", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxPrincipalPerCollateralAmount", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "mint", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "name", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "pauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "paused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceAdapter", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceRouteHash", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bytes32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "principalToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "redeem", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "repayLoanCallback", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "address", - "name": "repayer" - }, - { - "type": "uint256", - "name": "principalAmount" - }, - { - "type": "uint256", - "name": "interestAmount" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "setWithdrawDelayTime", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_seconds" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "sharesExchangeRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "sharesExchangeRateInverse", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "symbol", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalInterestCollected", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensCommitted", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensLended", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensWithdrawn", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalSupply", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transfer", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferFrom", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "from" - }, - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "withdraw", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "withdrawDelayTimeSeconds", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "withdrawFromEscrowVault", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amount" - } - ], - "outputs": [] - } - ], - "receipt": {}, - "numDeployments": 1, - "implementation": "0xF579ba9Ce33E392134Fd4a1A9D7D9d792eAF0B2b" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json deleted file mode 100644 index 6f0dfa35c..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json +++ /dev/null @@ -1,218 +0,0 @@ -{ - "address": "0x98eEbd694eE24935615BF18bA1ae75B2E486487f", - "abi": [ - { - "type": "event", - "anonymous": false, - "name": "DeployedLenderGroupContract", - "inputs": [ - { - "type": "address", - "name": "groupContract", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "deployLenderCommitmentGroupPool", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_initialPrincipalAmount" - }, - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "tuple[]", - "name": "_poolOracleRoutes", - "components": [ - { - "type": "address", - "name": "pool" - }, - { - "type": "bool", - "name": "zeroForOne" - }, - { - "type": "uint32", - "name": "twapInterval" - }, - { - "type": "uint256", - "name": "token0Decimals" - }, - { - "type": "uint256", - "name": "token1Decimals" - } - ] - } - ], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deployedLenderGroupContracts", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_lenderGroupBeacon" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "lenderGroupBeacon", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - } - ], - "transactionHash": "0xa8d2d589773b0db38e02cc7d27810432a440af30f9aaee53259319050b1f748a", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "blockHash": null, - "blockNumber": null - }, - "numDeployments": 1, - "implementation": "0x84E2ab3177045aF218FaDF4Aa5d9708F6773d37f" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json deleted file mode 100644 index 23b2c594a..000000000 --- a/packages/contracts/deployments/base/PriceAdapterAerodrome.json +++ /dev/null @@ -1,239 +0,0 @@ -{ - "address": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - }, - { - "indexed": false, - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "RouteRegistered", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "name": "decodePoolRoutes", - "outputs": [ - { - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "route_array", - "type": "tuple[]" - } - ], - "stateMutability": "pure", - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "routes", - "type": "tuple[]" - } - ], - "name": "encodePoolRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "encoded", - "type": "bytes" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "route", - "type": "bytes32" - } - ], - "name": "getPriceRatioQ96", - "outputs": [ - { - "internalType": "uint256", - "name": "priceRatioQ96", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "name": "priceRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "", - "type": "bytes" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "registerPriceRoute", - "outputs": [ - { - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "transactionHash": "0xda4bfa6b47ea07a051970fc4119cd23498e052b7f05d25e8026068d7c3df42f6", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0xb4D81863b0bDef8FF372d44c161a1a025d788A7a", - "transactionIndex": 252, - "gasUsed": "993855", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0xda11f9a6cf3a208e2079a20da271ed5ff66edc355e7d9c3155d16dbe850901c8", - "transactionHash": "0xda4bfa6b47ea07a051970fc4119cd23498e052b7f05d25e8026068d7c3df42f6", - "logs": [], - "blockNumber": 38359843, - "cumulativeGasUsed": "49442662", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "aa8b36c3500f06f65707aa97290d90c3", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", - "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b815260048101879052602481018290529091507398c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac7190637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "libraries": { - "FixedPointQ96": "0x98c1A3E3C0eDfef8db0f1525B07F92d4DFD4ac71" - }, - "devdoc": { - "kind": "dev", - "methods": {}, - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 76889, - "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", - "label": "priceRoutes", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_bytes32,t_bytes_storage)" - } - ], - "types": { - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_bytes_storage": { - "encoding": "bytes", - "label": "bytes", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_bytes_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bytes)", - "numberOfBytes": "32", - "value": "t_bytes_storage" - } - } - } -} \ No newline at end of file From 1ab3c646578fc52b0543b975a3340be2b01accf0 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 20 Nov 2025 14:56:59 -0500 Subject: [PATCH 32/46] improve PoolV3 reliance on lib --- .../contracts/.openzeppelin/unknown-8453.json | 511 +++++ .../LenderCommitmentGroup_Pool_V3.sol | 13 +- .../deploy/pricing/price_adapter_aerodrome.ts | 2 +- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 ++ .../base/LenderCommitmentGroupBeaconV3.json | 1893 +++++++++++++++++ .../base/LenderCommitmentGroupFactory_V3.json | 200 ++ .../base/PriceAdapterAerodrome.json | 239 +++ .../d2a445878acc07141df9a184837e8d0b.json | 986 +++++++++ 9 files changed, 3974 insertions(+), 8 deletions(-) create mode 100644 packages/contracts/deployments/base/FixedPointQ96.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json create mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json create mode 100644 packages/contracts/deployments/base/solcInputs/d2a445878acc07141df9a184837e8d0b.json diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index 8874c15c2..d72948959 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -9,6 +9,11 @@ "address": "0x98eEbd694eE24935615BF18bA1ae75B2E486487f", "txHash": "0xa8d2d589773b0db38e02cc7d27810432a440af30f9aaee53259319050b1f748a", "kind": "transparent" + }, + { + "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", + "txHash": "0x186bf874a4fafa3be5c28fac20f23248f0dc4fe545b72da2952e8826a6edfebf", + "kind": "transparent" } ], "impls": { @@ -108,6 +113,512 @@ }, "namespaces": {} } + }, + "b3b2ef84dc3d78ec1e7c891362c8a6c587afc8bced8981ce1305a0c2ec3f0d0a": { + "address": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", + "txHash": "0x4d3caf653e872755f1c220ac034dd93bc47845df90965de86812ce5ab2ba984e", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_status", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" + }, + { + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" + }, + { + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" + }, + { + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" + }, + { + "label": "poolSharesLastTransferredAt", + "offset": 0, + "slot": "201", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)50_storage", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" + }, + { + "label": "priceAdapter", + "offset": 0, + "slot": "252", + "type": "t_address", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:115" + }, + { + "label": "principalToken", + "offset": 0, + "slot": "253", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:119" + }, + { + "label": "collateralToken", + "offset": 0, + "slot": "254", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:120" + }, + { + "label": "marketId", + "offset": 0, + "slot": "255", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:122" + }, + { + "label": "totalPrincipalTokensCommitted", + "offset": 0, + "slot": "256", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:125" + }, + { + "label": "totalPrincipalTokensWithdrawn", + "offset": 0, + "slot": "257", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:126" + }, + { + "label": "totalPrincipalTokensLended", + "offset": 0, + "slot": "258", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:128" + }, + { + "label": "totalPrincipalTokensRepaid", + "offset": 0, + "slot": "259", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:129" + }, + { + "label": "excessivePrincipalTokensRepaid", + "offset": 0, + "slot": "260", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:130" + }, + { + "label": "totalInterestCollected", + "offset": 0, + "slot": "261", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:132" + }, + { + "label": "liquidityThresholdPercent", + "offset": 0, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:134" + }, + { + "label": "collateralRatio", + "offset": 2, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:135" + }, + { + "label": "maxLoanDuration", + "offset": 4, + "slot": "262", + "type": "t_uint32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:137" + }, + { + "label": "interestRateLowerBound", + "offset": 8, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:138" + }, + { + "label": "interestRateUpperBound", + "offset": 10, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:139" + }, + { + "label": "activeBids", + "offset": 0, + "slot": "263", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:147" + }, + { + "label": "activeBidsAmountDueRemaining", + "offset": 0, + "slot": "264", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:148" + }, + { + "label": "tokenDifferenceFromLiquidations", + "offset": 0, + "slot": "265", + "type": "t_int256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:150" + }, + { + "label": "firstDepositMade", + "offset": 0, + "slot": "266", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:152" + }, + { + "label": "withdrawDelayTimeSeconds", + "offset": 0, + "slot": "267", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:153" + }, + { + "label": "priceRouteHash", + "offset": 0, + "slot": "268", + "type": "t_bytes32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:157" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "offset": 0, + "slot": "269", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:161" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "270", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:164" + }, + { + "label": "paused", + "offset": 0, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:165" + }, + { + "label": "borrowingPaused", + "offset": 1, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:166" + }, + { + "label": "liquidationAuctionPaused", + "offset": 2, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:167" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)45_storage": { + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "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_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_int256": { + "label": "int256", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "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": {} + } + }, + "72849f8392a9e31ccd1fedb257f9a29aee0264b78017fa77eebd44ee6e559469": { + "address": "0x45F8eF370e6E3b83e2b592c149b7aB8a0c479A74", + "txHash": "0x9c33e645a2bd77216897a1c73e1fc161b5d72ecdbd5d6352ad4c4f27f2ff0287", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "lenderGroupBeacon", + "offset": 0, + "slot": "101", + "type": "t_address", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:32" + }, + { + "label": "deployedLenderGroupContracts", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:36" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } } } } diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol index 8edd12e77..f9473cbcc 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol @@ -30,12 +30,9 @@ import "../../../interfaces/IProtocolPausingManager.sol"; import "../../../interfaces/ISmartCommitmentForwarder.sol"; -import {FixedPointQ96} from "../../../libraries/FixedPointQ96.sol"; - - + -import "../../../libraries/uniswap/TickMath.sol"; -import "../../../libraries/uniswap/FixedPoint96.sol"; +import "../../../libraries/uniswap/TickMath.sol"; import "../../../libraries/uniswap/FullMath.sol"; @@ -100,6 +97,10 @@ contract LenderCommitmentGroup_Pool_V3 is using AddressUpgradeable for address; using NumbersLib for uint256; + + uint256 constant Q96 = 0x1000000000000000000000000; + + uint256 public immutable MIN_TWAP_INTERVAL = 3; @@ -748,7 +749,7 @@ contract LenderCommitmentGroup_Pool_V3 is return MathUpgradeable.mulDiv( _principalAmount, - FixedPointQ96.Q96, + Q96, _maxPrincipalPerCollateralAmountQ96, MathUpgradeable.Rounding.Up ); diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index a013c81cc..9edf10295 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -17,7 +17,7 @@ const deployFn: DeployFunction = async (hre) => { // need to add a delay , wait here ! - await tx.wait(1) // wait one block + // await tx.wait(1) // wait one block diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index b54efb620..0c05c40f7 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,5 +42,7 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216 + "timelock-controller:update-delay-7200": 1757524216, + "lender-commitment-group-beacon-v3:deploy": 1763666932, + "lender-commitment-group-factory-v3:deploy": 1763666939 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json new file mode 100644 index 000000000..dc46c68c4 --- /dev/null +++ b/packages/contracts/deployments/base/FixedPointQ96.json @@ -0,0 +1,134 @@ +{ + "address": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "divideFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "q96Value", + "type": "uint256" + } + ], + "name": "fromFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "multiplyFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "numerator", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "denominator", + "type": "uint256" + } + ], + "name": "toFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + } + ], + "transactionHash": "0xdb8542eec47eb8899f5a234be9e4f19139a037a16b0bb13357d5b73fa8cdc574", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619", + "transactionIndex": 200, + "gasUsed": "141837", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xa09a1ee73575ad06429068b22af5bf78f0cdea85552a4177d3345d35d0d7e67a", + "transactionHash": "0xdb8542eec47eb8899f5a234be9e4f19139a037a16b0bb13357d5b73fa8cdc574", + "logs": [], + "blockNumber": 38438797, + "cumulativeGasUsed": "34802686", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "d2a445878acc07141df9a184837e8d0b", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", + "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "devdoc": { + "kind": "dev", + "methods": {}, + "title": "FixedPoint96", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json new file mode 100644 index 000000000..9e292e588 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json @@ -0,0 +1,1893 @@ +{ + "address": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_WITHDRAW_DELAY_TIME", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "firstDepositMade", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapter" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceAdapter", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceRouteHash", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_seconds" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json new file mode 100644 index 000000000..ec592cc9c --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json @@ -0,0 +1,200 @@ +{ + "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapterAddress" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x186bf874a4fafa3be5c28fac20f23248f0dc4fe545b72da2952e8826a6edfebf", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x45F8eF370e6E3b83e2b592c149b7aB8a0c479A74" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json new file mode 100644 index 000000000..10977d806 --- /dev/null +++ b/packages/contracts/deployments/base/PriceAdapterAerodrome.json @@ -0,0 +1,239 @@ +{ + "address": "0xfA35A7DDEAf1eA98F0756B83FBf9Bf984bbbDb17", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x92e89965a01d5d1f566132e2e11b4aa1aed432f4e8dad0169f446be649d9a72e", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xfA35A7DDEAf1eA98F0756B83FBf9Bf984bbbDb17", + "transactionIndex": 167, + "gasUsed": "993855", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x021202e4b55515d0b444fee88ca006567b659e23b11e6e78ec0895ff27500975", + "transactionHash": "0x92e89965a01d5d1f566132e2e11b4aa1aed432f4e8dad0169f446be649d9a72e", + "logs": [], + "blockNumber": 38438832, + "cumulativeGasUsed": "26932969", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "d2a445878acc07141df9a184837e8d0b", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073EA2CC36731704Cb7B98C7CA9F891Ca42405a061990637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 76890, + "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/solcInputs/d2a445878acc07141df9a184837e8d0b.json b/packages/contracts/deployments/base/solcInputs/d2a445878acc07141df9a184837e8d0b.json new file mode 100644 index 000000000..6f6b8cdb4 --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/d2a445878acc07141df9a184837e8d0b.json @@ -0,0 +1,986 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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" + }, + "@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns an account's balance in the token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n FUNCTIONS\n //////////////////////////////////////////////////////////////*/\n\n /// @notice Owner balance of an id.\n /// @param owner The address of the owner.\n /// @param id The id of the token.\n /// @return amount The balance of the token.\n function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n /// @notice Spender allowance of an id.\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @return amount The allowance of the token.\n function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n /// @notice Checks if a spender is approved by an owner as an operator\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @return approved The approval status.\n function isOperator(address owner, address spender) external view returns (bool approved);\n\n /// @notice Transfers an amount of an id from the caller to a receiver.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Transfers an amount of an id from a sender to a receiver.\n /// @param sender The address of the sender.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Approves an amount of an id to a spender.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always\n function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Sets or removes an operator for the caller.\n /// @param operator The address of the operator.\n /// @param approved The approval status.\n /// @return bool True, always\n function setOperator(address operator, bool approved) external returns (bool);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExtsload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n /// @notice Called by external contracts to access granular pool state\n /// @param slot Key of slot to sload\n /// @return value The value of the slot as bytes32\n function extsload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access granular pool state\n /// @param startSlot Key of slot to start sloading from\n /// @param nSlots Number of slots to load into return value\n /// @return values List of loaded values.\n function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n /// @notice Called by external contracts to access sparse pool state\n /// @param slots List of slots to SLOAD from.\n /// @return values List of loaded values.\n function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExttload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n /// @notice Called by external contracts to access transient storage of the contract\n /// @param slot Key of slot to tload\n /// @return value The value of the slot as bytes32\n function exttload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access sparse transient pool state\n /// @param slots List of slots to tload\n /// @return values List of loaded values\n function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IHooks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n /// @notice The hook called before the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @return bytes4 The function selector for the hook\n function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n /// @notice The hook called after the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @param tick The current tick after the state of a pool is initialized\n /// @return bytes4 The function selector for the hook\n function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n external\n returns (bytes4);\n\n /// @notice The hook called before liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n external\n returns (bytes4, BeforeSwapDelta, uint24);\n\n /// @notice The hook called after a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterSwap(\n address sender,\n PoolKey calldata key,\n SwapParams calldata params,\n BalanceDelta delta,\n bytes calldata hookData\n ) external returns (bytes4, int128);\n\n /// @notice The hook called before donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function afterDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IPoolManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n /// @notice Thrown when a currency is not netted out after the contract is unlocked\n error CurrencyNotSettled();\n\n /// @notice Thrown when trying to interact with a non-initialized pool\n error PoolNotInitialized();\n\n /// @notice Thrown when unlock is called, but the contract is already unlocked\n error AlreadyUnlocked();\n\n /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n error ManagerLocked();\n\n /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n error TickSpacingTooLarge(int24 tickSpacing);\n\n /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n error TickSpacingTooSmall(int24 tickSpacing);\n\n /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n /// or on a pool that does not have a dynamic swap fee.\n error UnauthorizedDynamicLPFeeUpdate();\n\n /// @notice Thrown when trying to swap amount of 0\n error SwapAmountCannotBeZero();\n\n ///@notice Thrown when native currency is passed to a non native settlement\n error NonzeroNativeValue();\n\n /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n error MustClearExactPositiveDelta();\n\n /// @notice Emitted when a new pool is initialized\n /// @param id The abi encoded hash of the pool key struct for the new pool\n /// @param currency0 The first currency of the pool by address sort order\n /// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none\n /// @param sqrtPriceX96 The price of the pool on initialization\n /// @param tick The initial tick of the pool corresponding to the initialized price\n event Initialize(\n PoolId indexed id,\n Currency indexed currency0,\n Currency indexed currency1,\n uint24 fee,\n int24 tickSpacing,\n IHooks hooks,\n uint160 sqrtPriceX96,\n int24 tick\n );\n\n /// @notice Emitted when a liquidity position is modified\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that modified the pool\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param liquidityDelta The amount of liquidity that was added or removed\n /// @param salt The extra data to make positions unique\n event ModifyLiquidity(\n PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n );\n\n /// @notice Emitted for swaps between currency0 and currency1\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param amount0 The delta of the currency0 balance of the pool\n /// @param amount1 The delta of the currency1 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 the price of the pool after the swap\n /// @param fee The swap fee in hundredths of a bip\n event Swap(\n PoolId indexed id,\n address indexed sender,\n int128 amount0,\n int128 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick,\n uint24 fee\n );\n\n /// @notice Emitted for donations\n /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n /// @param sender The address that initiated the donate call\n /// @param amount0 The amount donated in currency0\n /// @param amount1 The amount donated in currency1\n event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n function unlock(bytes calldata data) external returns (bytes memory);\n\n /// @notice Initialize the state for a given pool ID\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The pool key for the pool to initialize\n /// @param sqrtPriceX96 The initial square root price\n /// @return tick The initial tick of the pool\n function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n /// @notice Modify the liquidity for the given pool\n /// @dev Poke by calling with a zero liquidityDelta\n /// @param key The pool to modify liquidity in\n /// @param params The parameters for modifying the liquidity\n /// @param hookData The data to pass through to the add/removeLiquidity hooks\n /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n /// @notice Swap against the given pool\n /// @param key The pool to swap in\n /// @param params The parameters for swapping\n /// @param hookData The data to pass through to the swap hooks\n /// @return swapDelta The balance delta of the address swapping\n /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta swapDelta);\n\n /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n /// Donors should keep this in mind when designing donation mechanisms.\n /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n /// Read the comments in `Pool.swap()` for more information about this.\n /// @param key The key of the pool to donate to\n /// @param amount0 The amount of currency0 to donate\n /// @param amount1 The amount of currency1 to donate\n /// @param hookData The data to pass through to the donate hooks\n /// @return BalanceDelta The delta of the caller after the donate\n function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n external\n returns (BalanceDelta);\n\n /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n /// for native tokens because the amount to settle is determined by the sent value.\n /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n /// native funds, this function can be called with the native currency to then be able to settle the native currency\n function sync(Currency currency) external;\n\n /// @notice Called by the user to net out some value owed to the user\n /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n /// @dev Can also be used as a mechanism for free flash loans\n /// @param currency The currency to withdraw from the pool manager\n /// @param to The address to withdraw to\n /// @param amount The amount of currency to withdraw\n function take(Currency currency, address to, uint256 amount) external;\n\n /// @notice Called by the user to pay what is owed\n /// @return paid The amount of currency settled\n function settle() external payable returns (uint256 paid);\n\n /// @notice Called by the user to pay on behalf of another address\n /// @param recipient The address to credit for the payment\n /// @return paid The amount of currency settled\n function settleFor(address recipient) external payable returns (uint256 paid);\n\n /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n /// @dev This could be used to clear a balance that is considered dust.\n /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n function clear(Currency currency, uint256 amount) external;\n\n /// @notice Called by the user to move value into ERC6909 balance\n /// @param to The address to mint the tokens to\n /// @param id The currency address to mint to ERC6909s, as a uint256\n /// @param amount The amount of currency to mint\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function mint(address to, uint256 id, uint256 amount) external;\n\n /// @notice Called by the user to move value from ERC6909 balance\n /// @param from The address to burn the tokens from\n /// @param id The currency address to burn from ERC6909s, as a uint256\n /// @param amount The amount of currency to burn\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function burn(address from, uint256 id, uint256 amount) external;\n\n /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The key of the pool to update dynamic LP fees for\n /// @param newDynamicLPFee The new dynamic pool LP fee\n function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IProtocolFees.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n /// @notice Thrown when protocol fee is set too high\n error ProtocolFeeTooLarge(uint24 fee);\n\n /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n error InvalidCaller();\n\n /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n error ProtocolFeeCurrencySynced();\n\n /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n /// @notice Emitted when the protocol fee is updated for a pool.\n event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n /// @notice Given a currency address, returns the protocol fees accrued in that currency\n /// @param currency The currency to check\n /// @return amount The amount of protocol fees accrued in the currency\n function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n /// @notice Sets the protocol fee for the given pool\n /// @param key The key of the pool to set a protocol fee for\n /// @param newProtocolFee The fee to set\n function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n /// @notice Sets the protocol fee controller\n /// @param controller The new protocol fee controller\n function setProtocolFeeController(address controller) external;\n\n /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n /// @dev This will revert if the contract is unlocked\n /// @param recipient The address to receive the protocol fees\n /// @param currency The currency to withdraw\n /// @param amount The amount of currency to withdraw\n /// @return amountCollected The amount of currency successfully withdrawn\n function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n external\n returns (uint256 amountCollected);\n\n /// @notice Returns the current protocol fee controller address\n /// @return address The current protocol fee controller address\n function protocolFeeController() external view returns (address);\n}\n" + }, + "@uniswap/v4-core/src/libraries/CustomRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n /// @dev ERC-7751 error for wrapping bubbled up reverts\n error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n /// @dev Reverts with the selector of a custom error in the scratch space\n function revertWith(bytes4 selector) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n revert(0, 0x04)\n }\n }\n\n /// @dev Reverts with a custom error with an address argument in the scratch space\n function revertWith(bytes4 selector, address addr) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with an int24 argument in the scratch space\n function revertWith(bytes4 selector, int24 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, signextend(2, value))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n function revertWith(bytes4 selector, uint160 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with two int24 arguments\n function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), signextend(2, value1))\n mstore(add(fmp, 0x24), signextend(2, value2))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two uint160 arguments\n function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two address arguments\n function revertWith(bytes4 selector, address value1, address value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n /// @dev this method can be vulnerable to revert data bombs\n function bubbleUpAndRevertWith(\n address revertingContract,\n bytes4 revertingFunctionSelector,\n bytes4 additionalContext\n ) internal pure {\n bytes4 wrappedErrorSelector = WrappedError.selector;\n assembly (\"memory-safe\") {\n // Ensure the size of the revert data is a multiple of 32 bytes\n let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n let fmp := mload(0x40)\n\n // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n mstore(fmp, wrappedErrorSelector)\n mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(\n add(fmp, 0x24),\n and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n // offset revert reason\n mstore(add(fmp, 0x44), 0x80)\n // offset additional context\n mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n // size revert reason\n mstore(add(fmp, 0x84), returndatasize())\n // revert reason\n returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n // size additional context\n mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n // additional context\n mstore(\n add(fmp, add(0xc4, encodedDataSize)),\n and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n revert(fmp, add(0xe4, encodedDataSize))\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/FixedPoint128.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n" + }, + "@uniswap/v4-core/src/libraries/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) internal pure returns (uint256 result) {\n unchecked {\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 = a * b; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(a, b, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n assembly (\"memory-safe\") {\n result := div(prod0, denominator)\n }\n return result;\n }\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 (\"memory-safe\") {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly (\"memory-safe\") {\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 = (0 - denominator) & denominator;\n // Divide denominator by power of two\n assembly (\"memory-safe\") {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly (\"memory-safe\") {\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 (\"memory-safe\") {\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 preconditions 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\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) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) != 0) {\n require(++result > 0);\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n assembly (\"memory-safe\") {\n z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n if shr(128, z) {\n // revert SafeCastOverflow()\n mstore(0, 0x93dafdf1)\n revert(0x1c, 0x04)\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/Position.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n using CustomRevert for bytes4;\n\n /// @notice Cannot update a position with no liquidity\n error CannotUpdateEmptyPosition();\n\n // info stored for each user's position\n struct State {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n }\n\n /// @notice Returns the State struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range\n /// @return position The position info struct of the given owners' position\n function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n view\n returns (State storage position)\n {\n bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n position = self[positionKey];\n }\n\n /// @notice A helper function to calculate the position key\n /// @param owner The address of the position owner\n /// @param tickLower the lower tick boundary of the position\n /// @param tickUpper the upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n pure\n returns (bytes32 positionKey)\n {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n mstore(fmp, owner) // [0x0c, 0x20)\n positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n // now clean the memory we used\n mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n mstore(fmp, 0) // fmp held owner\n }\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n /// @return feesOwed0 The amount of currency0 owed to the position owner\n /// @return feesOwed1 The amount of currency1 owed to the position owner\n function update(\n State storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n uint128 liquidity = self.liquidity;\n\n if (liquidityDelta == 0) {\n // disallow pokes for 0 liquidity positions\n if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n } else {\n self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n unchecked {\n feesOwed0 =\n FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n feesOwed1 =\n FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n }\n\n // update the position\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n using CustomRevert for bytes4;\n\n error SafeCastOverflow();\n\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint160\n function toUint160(uint256 x) internal pure returns (uint160 y) {\n y = uint160(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a uint128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint128\n function toUint128(uint256 x) internal pure returns (uint128 y) {\n y = uint128(x);\n if (x != y) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n /// @param x The int128 to be casted\n /// @return y The casted integer, now type uint128\n function toUint128(int128 x) internal pure returns (uint128 y) {\n if (x < 0) SafeCastOverflow.selector.revertWith();\n y = uint128(x);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param x The int256 to be downcasted\n /// @return y The downcasted integer, now type int128\n function toInt128(int256 x) internal pure returns (int128 y) {\n y = int128(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param x The uint256 to be casted\n /// @return y The casted integer, now type int256\n function toInt256(uint256 x) internal pure returns (int256 y) {\n y = int256(x);\n if (y < 0) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return The downcasted integer, now type int128\n function toInt128(uint256 x) internal pure returns (int128) {\n if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n return int128(int256(x));\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/StateLibrary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n /// @notice index of pools mapping in the PoolManager\n bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n /// @notice index of feeGrowthGlobal0X128 in Pool.State\n uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n /// @notice index of liquidity in Pool.State\n uint256 public constant LIQUIDITY_OFFSET = 3;\n\n /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n uint256 public constant TICKS_OFFSET = 4;\n\n /// @notice index of tickBitmap mapping in Pool.State\n uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n uint256 public constant POSITIONS_OFFSET = 6;\n\n /**\n * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n * @dev Corresponds to pools[poolId].slot0\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n * @return tick The current tick of the pool.\n * @return protocolFee The protocol fee of the pool.\n * @return lpFee The swap fee of the pool.\n */\n function getSlot0(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n bytes32 data = manager.extsload(stateSlot);\n\n // 24 bits |24bits|24bits |24 bits|160 bits\n // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n // ---------- | fee |protocolfee | tick | sqrtPriceX96\n assembly (\"memory-safe\") {\n // bottom 160 bits of data\n sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n // next 24 bits of data\n tick := signextend(2, shr(160, data))\n // next 24 bits of data\n protocolFee := and(shr(184, data), 0xFFFFFF)\n // last 24 bits of data\n lpFee := and(shr(208, data), 0xFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the tick information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve information for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n )\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // read all 3 words of the TickInfo struct\n bytes32[] memory data = manager.extsload(slot, 3);\n assembly (\"memory-safe\") {\n let firstWord := mload(add(data, 32))\n liquidityNet := sar(128, firstWord)\n liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n feeGrowthOutside0X128 := mload(add(data, 64))\n feeGrowthOutside1X128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve liquidity for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n */\n function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint128 liquidityGross, int128 liquidityNet)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n bytes32 value = manager.extsload(slot);\n assembly (\"memory-safe\") {\n liquidityNet := sar(128, value)\n liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the fee growth outside a tick range of a pool\n * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve fee growth for.\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // offset by 1 word, since the first word is liquidityGross + liquidityNet\n bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n assembly (\"memory-safe\") {\n feeGrowthOutside0X128 := mload(add(data, 32))\n feeGrowthOutside1X128 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves the global fee growth of a pool.\n * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return feeGrowthGlobal0 The global fee growth for token0.\n * @return feeGrowthGlobal1 The global fee growth for token1.\n * @dev Note that feeGrowthGlobal can be artificially inflated\n * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n */\n function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State, `uint256 feeGrowthGlobal0X128`\n bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n // read the 2 words of feeGrowthGlobal\n bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n assembly (\"memory-safe\") {\n feeGrowthGlobal0 := mload(add(data, 32))\n feeGrowthGlobal1 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves total the liquidity of a pool.\n * @dev Corresponds to pools[poolId].liquidity\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return liquidity The liquidity of the pool.\n */\n function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `uint128 liquidity`\n bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Retrieves the tick bitmap of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].tickBitmap[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve the bitmap for.\n * @return tickBitmap The bitmap of the tick.\n */\n function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n internal\n view\n returns (uint256 tickBitmap)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n tickBitmap = uint256(manager.extsload(slot));\n }\n\n /**\n * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param poolId The ID of the pool.\n * @param owner The owner of the liquidity position.\n * @param tickLower The lower tick of the liquidity range.\n * @param tickUpper The upper tick of the liquidity range.\n * @param salt The bytes32 randomness to further distinguish position state.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(\n IPoolManager manager,\n PoolId poolId,\n address owner,\n int24 tickLower,\n int24 tickUpper,\n bytes32 salt\n ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n }\n\n /**\n * @notice Retrieves the position information of a pool at a specific position ID.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n // read all 3 words of the Position.State struct\n bytes32[] memory data = manager.extsload(slot, 3);\n\n assembly (\"memory-safe\") {\n liquidity := mload(add(data, 32))\n feeGrowthInside0LastX128 := mload(add(data, 64))\n feeGrowthInside1LastX128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity of a position.\n * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n */\n function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Calculate the fee growth inside a tick range of a pool\n * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tickLower The lower tick of the range.\n * @param tickUpper The upper tick of the range.\n * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n */\n function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n internal\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n {\n (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickLower);\n (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickUpper);\n (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n unchecked {\n if (tickCurrent < tickLower) {\n feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n } else if (tickCurrent >= tickUpper) {\n feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n }\n }\n }\n\n function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n }\n\n function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int24 => TickInfo) ticks`\n bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n // slot key of the tick key: `pools[poolId].ticks[tick]\n return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n }\n\n function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(bytes32 => Position.State) positions;`\n bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n // slot of the mapping key: `pools[poolId].positions[positionId]\n return keccak256(abi.encodePacked(positionId, positionMapping));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BalanceDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n assembly (\"memory-safe\") {\n balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := add(a0, b0)\n res1 := add(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := sub(a0, b0)\n res1 := sub(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n /// @notice A BalanceDelta of 0\n BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n assembly (\"memory-safe\") {\n _amount0 := sar(128, balanceDelta)\n }\n }\n\n function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n assembly (\"memory-safe\") {\n _amount1 := signextend(15, balanceDelta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BeforeSwapDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n pure\n returns (BeforeSwapDelta beforeSwapDelta)\n{\n assembly (\"memory-safe\") {\n beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n /// @notice A BeforeSwapDelta of 0\n BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap\n function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n assembly (\"memory-safe\") {\n deltaSpecified := sar(128, delta)\n }\n }\n\n /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap and afterSwap\n function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n assembly (\"memory-safe\") {\n deltaUnspecified := signextend(15, delta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/Currency.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n error NativeTransferFailed();\n\n /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n error ERC20TransferFailed();\n\n /// @notice A constant to represent the native currency\n Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n function transfer(Currency currency, address to, uint256 amount) internal {\n // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n // modified custom error selectors\n\n bool success;\n if (currency.isAddressZero()) {\n assembly (\"memory-safe\") {\n // Transfer the ETH and revert if it fails.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n // revert with NativeTransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n }\n } else {\n assembly (\"memory-safe\") {\n // Get a pointer to some free memory.\n let fmp := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n success :=\n and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), currency, 0, fmp, 68, 0, 32)\n )\n\n // Now clean the memory we used\n mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n }\n // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(\n Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n );\n }\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return address(this).balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n }\n }\n\n function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return owner.balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n }\n }\n\n function isAddressZero(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n }\n\n function toId(Currency currency) internal pure returns (uint256) {\n return uint160(Currency.unwrap(currency));\n }\n\n // If the upper 12 bytes are non-zero, they will be zero-ed out\n // Therefore, fromId() and toId() are not inverses of each other\n function fromId(uint256 id) internal pure returns (Currency) {\n return Currency.wrap(address(uint160(id)));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolId.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n assembly (\"memory-safe\") {\n // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n poolId := keccak256(poolKey, 0xa0)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolKey.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n /// @notice The lower currency of the pool, sorted numerically\n Currency currency0;\n /// @notice The higher currency of the pool, sorted numerically\n Currency currency1;\n /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n uint24 fee;\n /// @notice Ticks that involve positions must be a multiple of tick spacing\n int24 tickSpacing;\n /// @notice The hooks of the pool\n IHooks hooks;\n}\n" + }, + "@uniswap/v4-core/src/types/PoolOperation.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // how to modify the liquidity\n int256 liquidityDelta;\n // a value to set if you want unique liquidity positions at the same range\n bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n /// Whether to swap token0 for token1 or vice versa\n bool zeroForOne;\n /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n int256 amountSpecified;\n /// The sqrt price at which, if reached, the swap will stop executing\n uint160 sqrtPriceLimitX96;\n}\n" + }, + "contracts/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\n}\n" + }, + "contracts/interfaces/defi/IAerodromePool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAerodromePool\n * @notice Defines the basic interface for an Aerodrome Pool.\n */\ninterface IAerodromePool {\n function lastObservation() external view returns (uint256, uint256, uint256);\n function observationLength() external view returns (uint256 );\n\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/ILenderCommitmentGroup_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V3 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n\n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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/IUniswapV4Pool.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 IUniswapV4Pool 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/interfaces/uniswapv4/IImmutableState.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n /// @notice The Uniswap v4 PoolManager contract\n function poolManager() external view returns (IPoolManager);\n}" + }, + "contracts/interfaces/uniswapv4/IStateView.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {PoolId} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {Position} from \"@uniswap/v4-core/src/libraries/Position.sol\";\nimport {IImmutableState} from \"./IImmutableState.sol\";\n\n/// @title IStateView\n/// @notice Interface for the StateView contract\ninterface IStateView is IImmutableState {\n /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n /// @dev Corresponds to pools[poolId].slot0\n /// @param poolId The ID of the pool.\n /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n /// @return tick The current tick of the pool.\n /// @return protocolFee The protocol fee of the pool.\n /// @return lpFee The swap fee of the pool.\n function getSlot0(PoolId poolId)\n external\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);\n\n /// @notice Retrieves the tick information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve information for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickInfo(PoolId poolId, int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n );\n\n /// @notice Retrieves the liquidity information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve liquidity for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function getTickLiquidity(PoolId poolId, int24 tick)\n external\n view\n returns (uint128 liquidityGross, int128 liquidityNet);\n\n /// @notice Retrieves the fee growth outside a tick range of a pool\n /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve fee growth for.\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickFeeGrowthOutside(PoolId poolId, int24 tick)\n external\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128);\n\n /// @notice Retrieves the global fee growth of a pool.\n /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n /// @param poolId The ID of the pool.\n /// @return feeGrowthGlobal0 The global fee growth for token0.\n /// @return feeGrowthGlobal1 The global fee growth for token1.\n function getFeeGrowthGlobals(PoolId poolId)\n external\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1);\n\n /// @notice Retrieves the total liquidity of a pool.\n /// @dev Corresponds to pools[poolId].liquidity\n /// @param poolId The ID of the pool.\n /// @return liquidity The liquidity of the pool.\n function getLiquidity(PoolId poolId) external view returns (uint128 liquidity);\n\n /// @notice Retrieves the tick bitmap of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].tickBitmap[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve the bitmap for.\n /// @return tickBitmap The bitmap of the tick.\n function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap);\n\n /// @notice Retrieves the position info without needing to calculate the `positionId`.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param owner The owner of the liquidity position.\n /// @param tickLower The lower tick of the liquidity range.\n /// @param tickUpper The upper tick of the liquidity range.\n /// @param salt The bytes32 randomness to further distinguish position state.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the position information of a pool at a specific position ID.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, bytes32 positionId)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the liquidity of a position.\n /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity);\n\n /// @notice Calculate the fee growth inside a tick range of a pool\n /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside\n /// @param poolId The ID of the pool.\n /// @param tickLower The lower tick of the range.\n /// @param tickUpper The upper tick of the range.\n /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper)\n external\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _priceAdapterAddress Address for the pool price adapter\n * @param _priceAdapterRoute Encoded roue for the price adapter \n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V3.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _priceAdapterAddress,\n _priceAdapterRoute\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\n\n} " + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.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 import \"../../../interfaces/IPriceAdapter.sol\";\n\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\nimport {FixedPointQ96} from \"../../../libraries/FixedPointQ96.sol\";\n\n\n\nimport \"../../../libraries/uniswap/TickMath.sol\";\nimport \"../../../libraries/uniswap/FixedPoint96.sol\";\nimport \"../../../libraries/uniswap/FullMath.sol\";\n \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\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_Pool_V3 is\n ILenderCommitmentGroup_V3,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\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 priceAdapter;\n \n \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 bytes32 public priceRouteHash;\n \n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW \n\n\n uint256 public lastUnpausedAt;\n bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n\n\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n\n \n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _priceAdapterRoute Route configuration for the principal/collateral oracle.\n\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n address _priceAdapter, \n \n bytes calldata _priceAdapterRoute\n\n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \n\n \n priceAdapter = _priceAdapter ;\n \n //internally this does checks and might revert \n // we register the price route with the adapter and save it locally \n priceRouteHash = IPriceAdapter( priceAdapter ).registerPriceRoute(\n _priceAdapterRoute\n );\n\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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\n \n // principalPerCollateralAmount\n uint256 priceRatioQ96 = IPriceAdapter( priceAdapter )\n .getPriceRatioQ96(priceRouteHash);\n \n \n \n\n return\n getRequiredCollateral(\n principalAmount,\n priceRatioQ96 // principalPerCollateralAmount \n );\n }\n\n \n \n\n /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 \n \n ) internal view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n FixedPointQ96.Q96,\n _maxPrincipalPerCollateralAmountQ96,\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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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 \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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Sets the delay time for withdrawing shares. 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 , \"WD\");\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"FDM\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"IC\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\");\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAerodrome.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAerodromePool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n import {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n\n\ncontract PriceAdapterAerodrome is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n // hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n // store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \n\n\n if (twapInterval == 0 ){\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\n\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \n }\n\n\n \n // Get two observations: current and one from twapInterval seconds ago\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = 0; // current\n secondsAgos[1] = twapInterval + 0 ; // oldest\n \n\n // Fetch observations\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\n\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\n\n // Calculate time-weighted average reserves\n uint256 timeElapsed = timestamp0 - timestamp1 ;\n require(timeElapsed > 0, \"Invalid time elapsed\");\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\n \n \n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\n\n\n\n\n }\n\n\n\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n\n }\n\n\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/*\n\n see https://docs.uniswap.org/contracts/v4/deployments \n\n\n https://docs.uniswap.org/contracts/v4/guides/read-pool-state\n\n\n\n*/\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\n\nimport {IStateView} from \"../interfaces/uniswapv4/IStateView.sol\";\n \nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\n\n\n\n\ncontract PriceAdapterUniswapV4 is\n IPriceAdapter\n\n{ \n\n \n\n using PoolIdLibrary for PoolKey;\n\n IPoolManager public immutable poolManager;\n\n\n using StateLibrary for IPoolManager;\n // address immutable POOL_MANAGER_V4; \n\n\n // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet \n //address immutable UNISWAP_V4_STATE_VIEW; \n\n struct PoolRoute {\n PoolId pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n \n\n constructor(IPoolManager _poolManager) {\n poolManager = _poolManager;\n }\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n function getPoolState(PoolId poolId) internal view returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint24 protocolFee,\n uint24 lpFee\n ) {\n return poolManager.getSlot0(poolId);\n }\n\n\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(PoolId poolId, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , ) = getPoolState(poolId);\n } else {\n\n revert(\"twap price not impl \");\n\n \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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 ea82f4b23c99481651e1edb123ba77ac6c9a5432 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 20 Nov 2025 14:57:34 -0500 Subject: [PATCH 33/46] reset migrations --- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 -- .../base/LenderCommitmentGroupBeaconV3.json | 1893 ----------------- .../base/LenderCommitmentGroupFactory_V3.json | 200 -- .../base/PriceAdapterAerodrome.json | 239 --- 5 files changed, 1 insertion(+), 2469 deletions(-) delete mode 100644 packages/contracts/deployments/base/FixedPointQ96.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json delete mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json delete mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index 0c05c40f7..b54efb620 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,7 +42,5 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216, - "lender-commitment-group-beacon-v3:deploy": 1763666932, - "lender-commitment-group-factory-v3:deploy": 1763666939 + "timelock-controller:update-delay-7200": 1757524216 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json deleted file mode 100644 index dc46c68c4..000000000 --- a/packages/contracts/deployments/base/FixedPointQ96.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "address": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619", - "abi": [ - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "divideFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "q96Value", - "type": "uint256" - } - ], - "name": "fromFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "fixedPointA", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "fixedPointB", - "type": "uint256" - } - ], - "name": "multiplyFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "numerator", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "denominator", - "type": "uint256" - } - ], - "name": "toFixedPoint96", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - } - ], - "transactionHash": "0xdb8542eec47eb8899f5a234be9e4f19139a037a16b0bb13357d5b73fa8cdc574", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619", - "transactionIndex": 200, - "gasUsed": "141837", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0xa09a1ee73575ad06429068b22af5bf78f0cdea85552a4177d3345d35d0d7e67a", - "transactionHash": "0xdb8542eec47eb8899f5a234be9e4f19139a037a16b0bb13357d5b73fa8cdc574", - "logs": [], - "blockNumber": 38438797, - "cumulativeGasUsed": "34802686", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "d2a445878acc07141df9a184837e8d0b", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", - "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", - "devdoc": { - "kind": "dev", - "methods": {}, - "title": "FixedPoint96", - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", - "version": 1 - }, - "storageLayout": { - "storage": [], - "types": null - } -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json deleted file mode 100644 index 9e292e588..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json +++ /dev/null @@ -1,1893 +0,0 @@ -{ - "address": "0x8Fe43B3b6d176aC892b787635c2F29dDa292B024", - "abi": [ - { - "type": "constructor", - "stateMutability": "undefined", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_tellerV2" - }, - { - "type": "address", - "name": "_smartCommitmentForwarder" - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Approval", - "inputs": [ - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "address", - "name": "spender", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "BorrowerAcceptedFunds", - "inputs": [ - { - "type": "address", - "name": "borrower", - "indexed": true - }, - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "collateralAmount", - "indexed": false - }, - { - "type": "uint32", - "name": "loanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRate", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "DefaultedLoanLiquidated", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "liquidator", - "indexed": true - }, - { - "type": "uint256", - "name": "amountDue", - "indexed": false - }, - { - "type": "int256", - "name": "tokenAmountDifference", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Deposit", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "LoanRepaid", - "inputs": [ - { - "type": "uint256", - "name": "bidId", - "indexed": true - }, - { - "type": "address", - "name": "repayer", - "indexed": true - }, - { - "type": "uint256", - "name": "principalAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "interestAmount", - "indexed": false - }, - { - "type": "uint256", - "name": "totalPrincipalRepaid", - "indexed": false - }, - { - "type": "uint256", - "name": "totalInterestCollected", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Paused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "PoolInitialized", - "inputs": [ - { - "type": "address", - "name": "principalTokenAddress", - "indexed": true - }, - { - "type": "address", - "name": "collateralTokenAddress", - "indexed": true - }, - { - "type": "uint256", - "name": "marketId", - "indexed": false - }, - { - "type": "uint32", - "name": "maxLoanDuration", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateLowerBound", - "indexed": false - }, - { - "type": "uint16", - "name": "interestRateUpperBound", - "indexed": false - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent", - "indexed": false - }, - { - "type": "uint16", - "name": "loanToValuePercent", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "SharesLastTransferredAt", - "inputs": [ - { - "type": "address", - "name": "recipient", - "indexed": true - }, - { - "type": "uint256", - "name": "transferredAt", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Transfer", - "inputs": [ - { - "type": "address", - "name": "from", - "indexed": true - }, - { - "type": "address", - "name": "to", - "indexed": true - }, - { - "type": "uint256", - "name": "value", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Unpaused", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedBorrowing", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "UnpausedLiquidationAuction", - "inputs": [ - { - "type": "address", - "name": "account", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Withdraw", - "inputs": [ - { - "type": "address", - "name": "caller", - "indexed": true - }, - { - "type": "address", - "name": "receiver", - "indexed": true - }, - { - "type": "address", - "name": "owner", - "indexed": true - }, - { - "type": "uint256", - "name": "assets", - "indexed": false - }, - { - "type": "uint256", - "name": "shares", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "WithdrawFromEscrow", - "inputs": [ - { - "type": "uint256", - "name": "amount", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "EXCHANGE_RATE_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MAX_WITHDRAW_DELAY_TIME", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "MIN_TWAP_INTERVAL", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "ORACLE_MANAGER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "SMART_COMMITMENT_FORWARDER", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "TELLER_V2", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "UNISWAP_EXPANSION_FACTOR", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "acceptFundsForAcceptBid", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_borrower" - }, - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "uint256", - "name": "_principalAmount" - }, - { - "type": "uint256", - "name": "_collateralAmount" - }, - { - "type": "address", - "name": "_collateralTokenAddress" - }, - { - "type": "uint256", - "name": "_collateralTokenId" - }, - { - "type": "uint32", - "name": "_loanDuration" - }, - { - "type": "uint16", - "name": "_interestRate" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "activeBids", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "activeBidsAmountDueRemaining", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "allowance", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - }, - { - "type": "address", - "name": "spender" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "approve", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "asset", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "assetTokenAddress" - } - ] - }, - { - "type": "function", - "name": "balanceOf", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "account" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "borrowingPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralRequiredToBorrowPrincipal", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "principalAmount" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "collateralTokensAmountToMatchValue" - } - ] - }, - { - "type": "function", - "name": "collateralRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "collateralToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "convertToShares", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decimals", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "decreaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "subtractedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deposit", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "excessivePrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "firstDepositMade", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getCollateralTokenType", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint8", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getLastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMarketId", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMaxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinInterestRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "amountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amountOwed" - }, - { - "type": "uint256", - "name": "_loanDefaultedTimestamp" - } - ], - "outputs": [ - { - "type": "int256", - "name": "amountDifference_" - } - ] - }, - { - "type": "function", - "name": "getPoolUtilizationRatio", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "activeLoansAmountDelta" - } - ], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalAmountAvailableToBorrow", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getPrincipalTokenAddress", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getSharesLastTransferredAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "getTokenDifferenceFromLiquidations", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "int256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "increaseAllowance", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "spender" - }, - { - "type": "uint256", - "name": "addedValue" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "address", - "name": "_priceAdapter" - }, - { - "type": "bytes", - "name": "_priceAdapterRoute" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "interestRateLowerBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "interestRateUpperBound", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "lastUnpausedAt", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidateDefaultedLoanWithIncentive", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "int256", - "name": "_tokenAmountDifference" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "liquidationAuctionPaused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "liquidityThresholdPercent", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint16", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxLoanDuration", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxPrincipalPerCollateralAmount", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "maxWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "mint", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "name", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "pauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "pausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "paused", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewDeposit", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewMint", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewRedeem", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "previewWithdraw", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceAdapter", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "priceRouteHash", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "bytes32", - "name": "" - } - ] - }, - { - "type": "function", - "name": "principalToken", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "redeem", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "shares" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "assets" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "repayLoanCallback", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_bidId" - }, - { - "type": "address", - "name": "repayer" - }, - { - "type": "uint256", - "name": "principalAmount" - }, - { - "type": "uint256", - "name": "interestAmount" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "setWithdrawDelayTime", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_seconds" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "sharesExchangeRate", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "sharesExchangeRateInverse", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "rate_" - } - ] - }, - { - "type": "function", - "name": "symbol", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "string", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalAssets", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalInterestCollected", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensCommitted", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensLended", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensRepaid", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalPrincipalTokensWithdrawn", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "totalSupply", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transfer", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferFrom", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "from" - }, - { - "type": "address", - "name": "to" - }, - { - "type": "uint256", - "name": "amount" - } - ], - "outputs": [ - { - "type": "bool", - "name": "" - } - ] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseBorrowing", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpauseLiquidationAuction", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "unpausePool", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "withdraw", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "assets" - }, - { - "type": "address", - "name": "receiver" - }, - { - "type": "address", - "name": "owner" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "shares" - } - ] - }, - { - "type": "function", - "name": "withdrawDelayTimeSeconds", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "withdrawFromEscrowVault", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_amount" - } - ], - "outputs": [] - } - ], - "receipt": {}, - "numDeployments": 1, - "implementation": "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json deleted file mode 100644 index ec592cc9c..000000000 --- a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json +++ /dev/null @@ -1,200 +0,0 @@ -{ - "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", - "abi": [ - { - "type": "event", - "anonymous": false, - "name": "DeployedLenderGroupContract", - "inputs": [ - { - "type": "address", - "name": "groupContract", - "indexed": true - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "Initialized", - "inputs": [ - { - "type": "uint8", - "name": "version", - "indexed": false - } - ] - }, - { - "type": "event", - "anonymous": false, - "name": "OwnershipTransferred", - "inputs": [ - { - "type": "address", - "name": "previousOwner", - "indexed": true - }, - { - "type": "address", - "name": "newOwner", - "indexed": true - } - ] - }, - { - "type": "function", - "name": "deployLenderCommitmentGroupPool", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "uint256", - "name": "_initialPrincipalAmount" - }, - { - "type": "tuple", - "name": "_commitmentGroupConfig", - "components": [ - { - "type": "address", - "name": "principalTokenAddress" - }, - { - "type": "address", - "name": "collateralTokenAddress" - }, - { - "type": "uint256", - "name": "marketId" - }, - { - "type": "uint32", - "name": "maxLoanDuration" - }, - { - "type": "uint16", - "name": "interestRateLowerBound" - }, - { - "type": "uint16", - "name": "interestRateUpperBound" - }, - { - "type": "uint16", - "name": "liquidityThresholdPercent" - }, - { - "type": "uint16", - "name": "collateralRatio" - } - ] - }, - { - "type": "address", - "name": "_priceAdapterAddress" - }, - { - "type": "bytes", - "name": "_priceAdapterRoute" - } - ], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "deployedLenderGroupContracts", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [ - { - "type": "address", - "name": "" - } - ], - "outputs": [ - { - "type": "uint256", - "name": "" - } - ] - }, - { - "type": "function", - "name": "initialize", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "_lenderGroupBeacon" - } - ], - "outputs": [] - }, - { - "type": "function", - "name": "lenderGroupBeacon", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "owner", - "constant": true, - "stateMutability": "view", - "payable": false, - "inputs": [], - "outputs": [ - { - "type": "address", - "name": "" - } - ] - }, - { - "type": "function", - "name": "renounceOwnership", - "constant": false, - "payable": false, - "inputs": [], - "outputs": [] - }, - { - "type": "function", - "name": "transferOwnership", - "constant": false, - "payable": false, - "inputs": [ - { - "type": "address", - "name": "newOwner" - } - ], - "outputs": [] - } - ], - "transactionHash": "0x186bf874a4fafa3be5c28fac20f23248f0dc4fe545b72da2952e8826a6edfebf", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "blockHash": null, - "blockNumber": null - }, - "numDeployments": 1, - "implementation": "0x45F8eF370e6E3b83e2b592c149b7aB8a0c479A74" -} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json deleted file mode 100644 index 10977d806..000000000 --- a/packages/contracts/deployments/base/PriceAdapterAerodrome.json +++ /dev/null @@ -1,239 +0,0 @@ -{ - "address": "0xfA35A7DDEAf1eA98F0756B83FBf9Bf984bbbDb17", - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - }, - { - "indexed": false, - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "RouteRegistered", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "name": "decodePoolRoutes", - "outputs": [ - { - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "route_array", - "type": "tuple[]" - } - ], - "stateMutability": "pure", - "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 PriceAdapterAerodrome.PoolRoute[]", - "name": "routes", - "type": "tuple[]" - } - ], - "name": "encodePoolRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "encoded", - "type": "bytes" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "route", - "type": "bytes32" - } - ], - "name": "getPriceRatioQ96", - "outputs": [ - { - "internalType": "uint256", - "name": "priceRatioQ96", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "name": "priceRoutes", - "outputs": [ - { - "internalType": "bytes", - "name": "", - "type": "bytes" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "route", - "type": "bytes" - } - ], - "name": "registerPriceRoute", - "outputs": [ - { - "internalType": "bytes32", - "name": "hash", - "type": "bytes32" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "transactionHash": "0x92e89965a01d5d1f566132e2e11b4aa1aed432f4e8dad0169f446be649d9a72e", - "receipt": { - "to": null, - "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", - "contractAddress": "0xfA35A7DDEAf1eA98F0756B83FBf9Bf984bbbDb17", - "transactionIndex": 167, - "gasUsed": "993855", - "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x021202e4b55515d0b444fee88ca006567b659e23b11e6e78ec0895ff27500975", - "transactionHash": "0x92e89965a01d5d1f566132e2e11b4aa1aed432f4e8dad0169f446be649d9a72e", - "logs": [], - "blockNumber": 38438832, - "cumulativeGasUsed": "26932969", - "status": 1, - "byzantium": true - }, - "args": [], - "numDeployments": 1, - "solcInputHash": "d2a445878acc07141df9a184837e8d0b", - "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", - "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073EA2CC36731704Cb7B98C7CA9F891Ca42405a061990637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", - "libraries": { - "FixedPointQ96": "0xEA2CC36731704Cb7B98C7CA9F891Ca42405a0619" - }, - "devdoc": { - "kind": "dev", - "methods": {}, - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 76890, - "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", - "label": "priceRoutes", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_bytes32,t_bytes_storage)" - } - ], - "types": { - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_bytes_storage": { - "encoding": "bytes", - "label": "bytes", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_bytes_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bytes)", - "numberOfBytes": "32", - "value": "t_bytes_storage" - } - } - } -} \ No newline at end of file From 1c73da1d6f809892e9882c0977105e93ed406e01 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 20 Nov 2025 14:59:16 -0500 Subject: [PATCH 34/46] deployed --- .../contracts/.openzeppelin/unknown-8453.json | 11 +- .../deployments/base/.migrations.json | 4 +- .../deployments/base/FixedPointQ96.json | 134 ++ .../base/LenderCommitmentGroupBeaconV3.json | 1893 +++++++++++++++++ .../base/LenderCommitmentGroupFactory_V3.json | 200 ++ .../base/PriceAdapterAerodrome.json | 239 +++ .../89630c6f3f81c242eebf75a043716f93.json | 986 +++++++++ 7 files changed, 3465 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/deployments/base/FixedPointQ96.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json create mode 100644 packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json create mode 100644 packages/contracts/deployments/base/PriceAdapterAerodrome.json create mode 100644 packages/contracts/deployments/base/solcInputs/89630c6f3f81c242eebf75a043716f93.json diff --git a/packages/contracts/.openzeppelin/unknown-8453.json b/packages/contracts/.openzeppelin/unknown-8453.json index d72948959..7a209e058 100644 --- a/packages/contracts/.openzeppelin/unknown-8453.json +++ b/packages/contracts/.openzeppelin/unknown-8453.json @@ -14,6 +14,11 @@ "address": "0x9B39b1dF550Db040cd67F52EEE927ab4cd42513b", "txHash": "0x186bf874a4fafa3be5c28fac20f23248f0dc4fe545b72da2952e8826a6edfebf", "kind": "transparent" + }, + { + "address": "0xD8D67872904Ee0778dFf44f05e6F2A7a246db10b", + "txHash": "0x6ec3f26b0bf4105a80bbe01a7e3d42bf4594237e9521f93a52ba40113f054309", + "kind": "transparent" } ], "impls": { @@ -521,7 +526,11 @@ } }, "namespaces": {} - } + }, + "allAddresses": [ + "0x1c644A1bCB658b718e76051cDE6A22cdb235a4fD", + "0x70136E7EE8423336D3063427f43ac425408ef6e1" + ] }, "72849f8392a9e31ccd1fedb257f9a29aee0264b78017fa77eebd44ee6e559469": { "address": "0x45F8eF370e6E3b83e2b592c149b7aB8a0c479A74", diff --git a/packages/contracts/deployments/base/.migrations.json b/packages/contracts/deployments/base/.migrations.json index b54efb620..071c50b9a 100644 --- a/packages/contracts/deployments/base/.migrations.json +++ b/packages/contracts/deployments/base/.migrations.json @@ -42,5 +42,7 @@ "uniswap-pricing-helper:deploy": 1755183533, "lender-commitment-group-beacon-v2:pricing-helper": 1755183533, "lender-commitment-forwarder:extensions:flash-swap-rollover:g2-upgrade": 1755270789, - "timelock-controller:update-delay-7200": 1757524216 + "timelock-controller:update-delay-7200": 1757524216, + "lender-commitment-group-beacon-v3:deploy": 1763668682, + "lender-commitment-group-factory-v3:deploy": 1763668685 } \ No newline at end of file diff --git a/packages/contracts/deployments/base/FixedPointQ96.json b/packages/contracts/deployments/base/FixedPointQ96.json new file mode 100644 index 000000000..dbc943503 --- /dev/null +++ b/packages/contracts/deployments/base/FixedPointQ96.json @@ -0,0 +1,134 @@ +{ + "address": "0x353F415320f6B5351e5516951F6eCb636CFcB4B9", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "divideFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "q96Value", + "type": "uint256" + } + ], + "name": "fromFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "multiplyFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "numerator", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "denominator", + "type": "uint256" + } + ], + "name": "toFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + } + ], + "transactionHash": "0x565d7f9f202187016142259c76e89ff54b3bc7e018b3a1f3b1f003b702c309cb", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x353F415320f6B5351e5516951F6eCb636CFcB4B9", + "transactionIndex": 228, + "gasUsed": "141837", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x0909abac81fe1899f8502491ad80c6240067fca7f611c6f5727474170c4454b3", + "transactionHash": "0x565d7f9f202187016142259c76e89ff54b3bc7e018b3a1f3b1f003b702c309cb", + "logs": [], + "blockNumber": 38439670, + "cumulativeGasUsed": "62608555", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "89630c6f3f81c242eebf75a043716f93", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", + "bytecode": "0x610199610035600b8282823980515f1a60731461002957634e487b7160e01b5f525f60045260245ffd5b305f52607381538281f3fe7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "deployedBytecode": "0x7300000000000000000000000000000000000000003014608060405260043610610055575f3560e01c80630f55b8251461005957806312b28bda1461007e5780637038961414610091578063c9bcd4f41461007e575b5f80fd5b61006c6100673660046100ea565b6100a4565b60405190815260200160405180910390f35b61006c61008c366004610101565b6100b9565b61006c61009f366004610101565b6100da565b5f6100b3600160601b83610121565b92915050565b5f816100c9600160601b85610140565b6100d39190610121565b9392505050565b5f600160601b6100c98385610140565b5f602082840312156100fa575f80fd5b5035919050565b5f8060408385031215610112575f80fd5b50508035926020909101359150565b5f8261013b57634e487b7160e01b5f52601260045260245ffd5b500490565b80820281158282048414176100b357634e487b7160e01b5f52601160045260245ffdfea2646970667358221220679c3bef9df8de48cf332d15e25a2762189a9ceb0a255109fe3884b5387cd8ea64736f6c63430008180033", + "devdoc": { + "kind": "dev", + "methods": {}, + "title": "FixedPoint96", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json new file mode 100644 index 000000000..6a21f16d7 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupBeaconV3.json @@ -0,0 +1,1893 @@ +{ + "address": "0x66c6FB4915F439B19B118Bdd01513365e0ab2B45", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_WITHDRAW_DELAY_TIME", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "firstDepositMade", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapter" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceAdapter", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceRouteHash", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_seconds" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0x70136E7EE8423336D3063427f43ac425408ef6e1" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json new file mode 100644 index 000000000..18cdd89c5 --- /dev/null +++ b/packages/contracts/deployments/base/LenderCommitmentGroupFactory_V3.json @@ -0,0 +1,200 @@ +{ + "address": "0xD8D67872904Ee0778dFf44f05e6F2A7a246db10b", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapterAddress" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x6ec3f26b0bf4105a80bbe01a7e3d42bf4594237e9521f93a52ba40113f054309", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x45F8eF370e6E3b83e2b592c149b7aB8a0c479A74" +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/PriceAdapterAerodrome.json b/packages/contracts/deployments/base/PriceAdapterAerodrome.json new file mode 100644 index 000000000..53001e816 --- /dev/null +++ b/packages/contracts/deployments/base/PriceAdapterAerodrome.json @@ -0,0 +1,239 @@ +{ + "address": "0xABdD07805240BEDF3CFECdC648DC2Fe1c12BBBb5", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterAerodrome.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x909d2c5226ab7d5b70bc7b8fabb3789e9149e624e58b21b369efc1200b12136e", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xABdD07805240BEDF3CFECdC648DC2Fe1c12BBBb5", + "transactionIndex": 222, + "gasUsed": "993855", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x26bb4ea21dc42e3bac985b24f9e8f0d9e76f82f1d85252d449691f217c3f09f1", + "transactionHash": "0x909d2c5226ab7d5b70bc7b8fabb3789e9149e624e58b21b369efc1200b12136e", + "logs": [], + "blockNumber": 38439675, + "cumulativeGasUsed": "42257867", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "89630c6f3f81c242eebf75a043716f93", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAerodrome.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAerodrome.sol\":\"PriceAdapterAerodrome\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAerodromePool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAerodromePool\\n * @notice Defines the basic interface for an Aerodrome Pool.\\n */\\ninterface IAerodromePool {\\n function lastObservation() external view returns (uint256, uint256, uint256);\\n function observationLength() external view returns (uint256 );\\n\\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\\n\\n function token0() external view returns (address);\\n\\n function token1() external view returns (address);\\n}\\n\",\"keccak256\":\"0x22a8cfa84ef56fb315a48717f355c1d5d85fc7c0288a6439869c0bd77fd0939d\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"contracts/libraries/erc4626/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // Divide x * y by the denominator.\\n z := div(mul(x, y), denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\\n revert(0, 0)\\n }\\n\\n // If x * y modulo the denominator is strictly greater than 0,\\n // 1 is added to round up the division of x * y by the denominator.\\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\",\"keccak256\":\"0xdbc49c04fd5a386c835e72ac4a77507e59d7a7c58290655b4cff2c4152fd4f65\",\"license\":\"AGPL-3.0-only\"},\"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\"},\"contracts/price_adapters/PriceAdapterAerodrome.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAerodromePool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n import {FixedPointMathLib} from \\\"../libraries/erc4626/utils/FixedPointMathLib.sol\\\";\\n\\n\\n\\ncontract PriceAdapterAerodrome is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n // hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n // store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n\\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \\n\\n\\n if (twapInterval == 0 ){\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\\n\\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \\n }\\n\\n\\n \\n // Get two observations: current and one from twapInterval seconds ago\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = 0; // current\\n secondsAgos[1] = twapInterval + 0 ; // oldest\\n \\n\\n // Fetch observations\\n \\n\\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\\n\\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\\n\\n // Calculate time-weighted average reserves\\n uint256 timeElapsed = timestamp0 - timestamp1 ;\\n require(timeElapsed > 0, \\\"Invalid time elapsed\\\");\\n\\n // Average reserves over the interval -- divisor isnt exactly right ? \\n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\\n \\n \\n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \\n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\\n\\n\\n\\n\\n }\\n\\n\\n\\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n\\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\\n\\n sqrtPriceX96 = uint160(\\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\\n );\\n\\n }\\n\\n\\n\\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x15f541cda3864d0f486e22a89f8f01aaa2ebb9f06f839057730963a27bc32f0d\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561000f575f80fd5b506110ff8061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073353F415320f6B5351e5516951F6eCb636CFcB4B990637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610a77565b6100e9565b6040516100799190610ad1565b60405180910390f35b610095610090366004610a77565b610180565b604051908152602001610079565b61006c6100b1366004610ba9565b610330565b6100956100c4366004610c94565b610359565b6100dc6100d7366004610c94565b6103cb565b6040516100799190610d23565b5f602081905290815260409020805461010190610da1565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610da1565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610da1565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610da1565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a826103cb565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610dd9565b6020026020010151610445565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610ded565b945050600101610275565b505050919050565b6060816040516020016103439190610d23565b6040516020818303038152906040529050919050565b5f80610364836103cb565b83516020808601919091205f8181529182905260409091209192509061038a8582610e50565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d481856040516103bc929190610f10565b60405180910390a19392505050565b6060818060200190518101906103e19190610f30565b90508051600114806103f4575080516002145b6104405760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f80610458835f0151846040015161048b565b90506104638161081c565b602084015190925015801561048457610481600160601b8085610831565b92505b5050919050565b5f806001846001600160a01b031663ebeb31db6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104ef9190610ded565b6104f9919061101e565b90508263ffffffff165f036105ba575f80806001600160a01b03871663252c09d761052560018761101e565b6040518263ffffffff1660e01b815260040161054391815260200190565b606060405180830381865afa15801561055e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105829190611031565b919450925090505f610594858461105c565b90505f6105a1868461105c565b90506105ad82826109a2565b9650505050505050610816565b6040805160028082526060820183525f926020830190803683370190505090505f815f815181106105ed576105ed610dd9565b63ffffffff9092166020928302919091019091015261060c845f61107b565b8160018151811061061f5761061f610dd9565b602002602001019063ffffffff16908163ffffffff16815250505f805f876001600160a01b031663252c09d7855f8151811061065d5761065d610dd9565b602002602001015163ffffffff1687610676919061101e565b6040518263ffffffff1660e01b815260040161069491815260200190565b606060405180830381865afa1580156106af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106d39190611031565b9250925092505f805f8a6001600160a01b031663252c09d7886001815181106106fe576106fe610dd9565b602002602001015163ffffffff168a610717919061101e565b6040518263ffffffff1660e01b815260040161073591815260200190565b606060405180830381865afa158015610750573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107749190611031565b919450925090505f610786848861101e565b90505f81116107ce5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a59081d1a5b5948195b185c1cd95960621b6044820152606401610257565b5f896107da858961101e565b6107e4919061105c565b90505f8a6107f2858961101e565b6107fc919061105c565b905061080882826109a2565b9b5050505050505050505050505b92915050565b5f6108166001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f03610865575f841161085a575f80fd5b50829004905061099b565b808411610870575f80fd5b5f848688098084039381119092039190505f8561088f8119600161109f565b16958690049593849004935f8190030460010190506108ae81846110b2565b909317925f6108be8760036110b2565b60021890506108cd81886110b2565b6108d890600261101e565b6108e290826110b2565b90506108ee81886110b2565b6108f990600261101e565b61090390826110b2565b905061090f81886110b2565b61091a90600261101e565b61092490826110b2565b905061093081886110b2565b61093b90600261101e565b61094590826110b2565b905061095181886110b2565b61095c90600261101e565b61096690826110b2565b905061097281886110b2565b61097d90600261101e565b61098790826110b2565b905061099381866110b2565b955050505050505b9392505050565b5f806109ad836109d3565b90505f6109b9856109d3565b90506109ca82600160601b83610831565b95945050505050565b60b581600160881b81106109ec5760409190911b9060801c5b69010000000000000000008110610a085760209190911b9060401c5b650100000000008110610a205760109190911b9060201c5b63010000008110610a365760089190911b9060101c5b62010000010260121c80820401600190811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b5f60208284031215610a87575f80fd5b5035919050565b5f81518084525f5b81811015610ab257602081850181015186830182015201610a96565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61099b6020830184610a8e565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610b1a57610b1a610ae3565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610b4957610b49610ae3565b604052919050565b5f67ffffffffffffffff821115610b6a57610b6a610ae3565b5060051b60200190565b6001600160a01b0381168114610b88575f80fd5b50565b8015158114610b88575f80fd5b63ffffffff81168114610b88575f80fd5b5f6020808385031215610bba575f80fd5b823567ffffffffffffffff811115610bd0575f80fd5b8301601f81018513610be0575f80fd5b8035610bf3610bee82610b51565b610b20565b81815260a09182028301840191848201919088841115610c11575f80fd5b938501935b83851015610c885780858a031215610c2c575f80fd5b610c34610af7565b8535610c3f81610b74565b815285870135610c4e81610b8b565b81880152604086810135610c6181610b98565b90820152606086810135908201526080808701359082015283529384019391850191610c16565b50979650505050505050565b5f6020808385031215610ca5575f80fd5b823567ffffffffffffffff80821115610cbc575f80fd5b818501915085601f830112610ccf575f80fd5b813581811115610ce157610ce1610ae3565b610cf3601f8201601f19168501610b20565b91508082528684828501011115610d08575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610d9457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610d3f565b5091979650505050505050565b600181811c90821680610db557607f821691505b602082108103610dd357634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610dfd575f80fd5b5051919050565b601f821115610e4b57805f5260205f20601f840160051c81016020851015610e295750805b601f840160051c820191505b81811015610e48575f8155600101610e35565b50505b505050565b815167ffffffffffffffff811115610e6a57610e6a610ae3565b610e7e81610e788454610da1565b84610e04565b602080601f831160018114610eb1575f8415610e9a5750858301515b5f19600386901b1c1916600185901b178555610f08565b5f85815260208120601f198616915b82811015610edf57888601518255948401946001909101908401610ec0565b5085821015610efc57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f610f286040830184610a8e565b949350505050565b5f6020808385031215610f41575f80fd5b825167ffffffffffffffff811115610f57575f80fd5b8301601f81018513610f67575f80fd5b8051610f75610bee82610b51565b81815260a09182028301840191848201919088841115610f93575f80fd5b938501935b83851015610c885780858a031215610fae575f80fd5b610fb6610af7565b8551610fc181610b74565b815285870151610fd081610b8b565b81880152604086810151610fe381610b98565b90820152606086810151908201526080808701519082015283529384019391850191610f98565b634e487b7160e01b5f52601160045260245ffd5b818103818111156108165761081661100a565b5f805f60608486031215611043575f80fd5b8351925060208401519150604084015190509250925092565b5f8261107657634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff8181168382160190808211156110985761109861100a565b5092915050565b808201808211156108165761081661100a565b80820281158282048414176108165761081661100a56fea2646970667358221220117e15d02070b6b2d0464584a0eac22dde1c5ae83359a80476802d82fd1f3fba64736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0x353F415320f6B5351e5516951F6eCb636CFcB4B9" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 76890, + "contract": "contracts/price_adapters/PriceAdapterAerodrome.sol:PriceAdapterAerodrome", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/solcInputs/89630c6f3f81c242eebf75a043716f93.json b/packages/contracts/deployments/base/solcInputs/89630c6f3f81c242eebf75a043716f93.json new file mode 100644 index 000000000..175bef38c --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/89630c6f3f81c242eebf75a043716f93.json @@ -0,0 +1,986 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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" + }, + "@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns an account's balance in the token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n FUNCTIONS\n //////////////////////////////////////////////////////////////*/\n\n /// @notice Owner balance of an id.\n /// @param owner The address of the owner.\n /// @param id The id of the token.\n /// @return amount The balance of the token.\n function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n /// @notice Spender allowance of an id.\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @return amount The allowance of the token.\n function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n /// @notice Checks if a spender is approved by an owner as an operator\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @return approved The approval status.\n function isOperator(address owner, address spender) external view returns (bool approved);\n\n /// @notice Transfers an amount of an id from the caller to a receiver.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Transfers an amount of an id from a sender to a receiver.\n /// @param sender The address of the sender.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Approves an amount of an id to a spender.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always\n function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Sets or removes an operator for the caller.\n /// @param operator The address of the operator.\n /// @param approved The approval status.\n /// @return bool True, always\n function setOperator(address operator, bool approved) external returns (bool);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExtsload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n /// @notice Called by external contracts to access granular pool state\n /// @param slot Key of slot to sload\n /// @return value The value of the slot as bytes32\n function extsload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access granular pool state\n /// @param startSlot Key of slot to start sloading from\n /// @param nSlots Number of slots to load into return value\n /// @return values List of loaded values.\n function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n /// @notice Called by external contracts to access sparse pool state\n /// @param slots List of slots to SLOAD from.\n /// @return values List of loaded values.\n function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExttload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n /// @notice Called by external contracts to access transient storage of the contract\n /// @param slot Key of slot to tload\n /// @return value The value of the slot as bytes32\n function exttload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access sparse transient pool state\n /// @param slots List of slots to tload\n /// @return values List of loaded values\n function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IHooks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n /// @notice The hook called before the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @return bytes4 The function selector for the hook\n function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n /// @notice The hook called after the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @param tick The current tick after the state of a pool is initialized\n /// @return bytes4 The function selector for the hook\n function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n external\n returns (bytes4);\n\n /// @notice The hook called before liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n external\n returns (bytes4, BeforeSwapDelta, uint24);\n\n /// @notice The hook called after a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterSwap(\n address sender,\n PoolKey calldata key,\n SwapParams calldata params,\n BalanceDelta delta,\n bytes calldata hookData\n ) external returns (bytes4, int128);\n\n /// @notice The hook called before donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function afterDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IPoolManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n /// @notice Thrown when a currency is not netted out after the contract is unlocked\n error CurrencyNotSettled();\n\n /// @notice Thrown when trying to interact with a non-initialized pool\n error PoolNotInitialized();\n\n /// @notice Thrown when unlock is called, but the contract is already unlocked\n error AlreadyUnlocked();\n\n /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n error ManagerLocked();\n\n /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n error TickSpacingTooLarge(int24 tickSpacing);\n\n /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n error TickSpacingTooSmall(int24 tickSpacing);\n\n /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n /// or on a pool that does not have a dynamic swap fee.\n error UnauthorizedDynamicLPFeeUpdate();\n\n /// @notice Thrown when trying to swap amount of 0\n error SwapAmountCannotBeZero();\n\n ///@notice Thrown when native currency is passed to a non native settlement\n error NonzeroNativeValue();\n\n /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n error MustClearExactPositiveDelta();\n\n /// @notice Emitted when a new pool is initialized\n /// @param id The abi encoded hash of the pool key struct for the new pool\n /// @param currency0 The first currency of the pool by address sort order\n /// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none\n /// @param sqrtPriceX96 The price of the pool on initialization\n /// @param tick The initial tick of the pool corresponding to the initialized price\n event Initialize(\n PoolId indexed id,\n Currency indexed currency0,\n Currency indexed currency1,\n uint24 fee,\n int24 tickSpacing,\n IHooks hooks,\n uint160 sqrtPriceX96,\n int24 tick\n );\n\n /// @notice Emitted when a liquidity position is modified\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that modified the pool\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param liquidityDelta The amount of liquidity that was added or removed\n /// @param salt The extra data to make positions unique\n event ModifyLiquidity(\n PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n );\n\n /// @notice Emitted for swaps between currency0 and currency1\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param amount0 The delta of the currency0 balance of the pool\n /// @param amount1 The delta of the currency1 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 the price of the pool after the swap\n /// @param fee The swap fee in hundredths of a bip\n event Swap(\n PoolId indexed id,\n address indexed sender,\n int128 amount0,\n int128 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick,\n uint24 fee\n );\n\n /// @notice Emitted for donations\n /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n /// @param sender The address that initiated the donate call\n /// @param amount0 The amount donated in currency0\n /// @param amount1 The amount donated in currency1\n event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n function unlock(bytes calldata data) external returns (bytes memory);\n\n /// @notice Initialize the state for a given pool ID\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The pool key for the pool to initialize\n /// @param sqrtPriceX96 The initial square root price\n /// @return tick The initial tick of the pool\n function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n /// @notice Modify the liquidity for the given pool\n /// @dev Poke by calling with a zero liquidityDelta\n /// @param key The pool to modify liquidity in\n /// @param params The parameters for modifying the liquidity\n /// @param hookData The data to pass through to the add/removeLiquidity hooks\n /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n /// @notice Swap against the given pool\n /// @param key The pool to swap in\n /// @param params The parameters for swapping\n /// @param hookData The data to pass through to the swap hooks\n /// @return swapDelta The balance delta of the address swapping\n /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta swapDelta);\n\n /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n /// Donors should keep this in mind when designing donation mechanisms.\n /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n /// Read the comments in `Pool.swap()` for more information about this.\n /// @param key The key of the pool to donate to\n /// @param amount0 The amount of currency0 to donate\n /// @param amount1 The amount of currency1 to donate\n /// @param hookData The data to pass through to the donate hooks\n /// @return BalanceDelta The delta of the caller after the donate\n function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n external\n returns (BalanceDelta);\n\n /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n /// for native tokens because the amount to settle is determined by the sent value.\n /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n /// native funds, this function can be called with the native currency to then be able to settle the native currency\n function sync(Currency currency) external;\n\n /// @notice Called by the user to net out some value owed to the user\n /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n /// @dev Can also be used as a mechanism for free flash loans\n /// @param currency The currency to withdraw from the pool manager\n /// @param to The address to withdraw to\n /// @param amount The amount of currency to withdraw\n function take(Currency currency, address to, uint256 amount) external;\n\n /// @notice Called by the user to pay what is owed\n /// @return paid The amount of currency settled\n function settle() external payable returns (uint256 paid);\n\n /// @notice Called by the user to pay on behalf of another address\n /// @param recipient The address to credit for the payment\n /// @return paid The amount of currency settled\n function settleFor(address recipient) external payable returns (uint256 paid);\n\n /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n /// @dev This could be used to clear a balance that is considered dust.\n /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n function clear(Currency currency, uint256 amount) external;\n\n /// @notice Called by the user to move value into ERC6909 balance\n /// @param to The address to mint the tokens to\n /// @param id The currency address to mint to ERC6909s, as a uint256\n /// @param amount The amount of currency to mint\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function mint(address to, uint256 id, uint256 amount) external;\n\n /// @notice Called by the user to move value from ERC6909 balance\n /// @param from The address to burn the tokens from\n /// @param id The currency address to burn from ERC6909s, as a uint256\n /// @param amount The amount of currency to burn\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function burn(address from, uint256 id, uint256 amount) external;\n\n /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The key of the pool to update dynamic LP fees for\n /// @param newDynamicLPFee The new dynamic pool LP fee\n function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IProtocolFees.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n /// @notice Thrown when protocol fee is set too high\n error ProtocolFeeTooLarge(uint24 fee);\n\n /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n error InvalidCaller();\n\n /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n error ProtocolFeeCurrencySynced();\n\n /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n /// @notice Emitted when the protocol fee is updated for a pool.\n event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n /// @notice Given a currency address, returns the protocol fees accrued in that currency\n /// @param currency The currency to check\n /// @return amount The amount of protocol fees accrued in the currency\n function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n /// @notice Sets the protocol fee for the given pool\n /// @param key The key of the pool to set a protocol fee for\n /// @param newProtocolFee The fee to set\n function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n /// @notice Sets the protocol fee controller\n /// @param controller The new protocol fee controller\n function setProtocolFeeController(address controller) external;\n\n /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n /// @dev This will revert if the contract is unlocked\n /// @param recipient The address to receive the protocol fees\n /// @param currency The currency to withdraw\n /// @param amount The amount of currency to withdraw\n /// @return amountCollected The amount of currency successfully withdrawn\n function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n external\n returns (uint256 amountCollected);\n\n /// @notice Returns the current protocol fee controller address\n /// @return address The current protocol fee controller address\n function protocolFeeController() external view returns (address);\n}\n" + }, + "@uniswap/v4-core/src/libraries/CustomRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n /// @dev ERC-7751 error for wrapping bubbled up reverts\n error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n /// @dev Reverts with the selector of a custom error in the scratch space\n function revertWith(bytes4 selector) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n revert(0, 0x04)\n }\n }\n\n /// @dev Reverts with a custom error with an address argument in the scratch space\n function revertWith(bytes4 selector, address addr) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with an int24 argument in the scratch space\n function revertWith(bytes4 selector, int24 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, signextend(2, value))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n function revertWith(bytes4 selector, uint160 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with two int24 arguments\n function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), signextend(2, value1))\n mstore(add(fmp, 0x24), signextend(2, value2))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two uint160 arguments\n function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two address arguments\n function revertWith(bytes4 selector, address value1, address value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n /// @dev this method can be vulnerable to revert data bombs\n function bubbleUpAndRevertWith(\n address revertingContract,\n bytes4 revertingFunctionSelector,\n bytes4 additionalContext\n ) internal pure {\n bytes4 wrappedErrorSelector = WrappedError.selector;\n assembly (\"memory-safe\") {\n // Ensure the size of the revert data is a multiple of 32 bytes\n let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n let fmp := mload(0x40)\n\n // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n mstore(fmp, wrappedErrorSelector)\n mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(\n add(fmp, 0x24),\n and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n // offset revert reason\n mstore(add(fmp, 0x44), 0x80)\n // offset additional context\n mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n // size revert reason\n mstore(add(fmp, 0x84), returndatasize())\n // revert reason\n returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n // size additional context\n mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n // additional context\n mstore(\n add(fmp, add(0xc4, encodedDataSize)),\n and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n revert(fmp, add(0xe4, encodedDataSize))\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/FixedPoint128.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n" + }, + "@uniswap/v4-core/src/libraries/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) internal pure returns (uint256 result) {\n unchecked {\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 = a * b; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(a, b, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n assembly (\"memory-safe\") {\n result := div(prod0, denominator)\n }\n return result;\n }\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 (\"memory-safe\") {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly (\"memory-safe\") {\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 = (0 - denominator) & denominator;\n // Divide denominator by power of two\n assembly (\"memory-safe\") {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly (\"memory-safe\") {\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 (\"memory-safe\") {\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 preconditions 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\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) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) != 0) {\n require(++result > 0);\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n assembly (\"memory-safe\") {\n z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n if shr(128, z) {\n // revert SafeCastOverflow()\n mstore(0, 0x93dafdf1)\n revert(0x1c, 0x04)\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/Position.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n using CustomRevert for bytes4;\n\n /// @notice Cannot update a position with no liquidity\n error CannotUpdateEmptyPosition();\n\n // info stored for each user's position\n struct State {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n }\n\n /// @notice Returns the State struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range\n /// @return position The position info struct of the given owners' position\n function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n view\n returns (State storage position)\n {\n bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n position = self[positionKey];\n }\n\n /// @notice A helper function to calculate the position key\n /// @param owner The address of the position owner\n /// @param tickLower the lower tick boundary of the position\n /// @param tickUpper the upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n pure\n returns (bytes32 positionKey)\n {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n mstore(fmp, owner) // [0x0c, 0x20)\n positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n // now clean the memory we used\n mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n mstore(fmp, 0) // fmp held owner\n }\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n /// @return feesOwed0 The amount of currency0 owed to the position owner\n /// @return feesOwed1 The amount of currency1 owed to the position owner\n function update(\n State storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n uint128 liquidity = self.liquidity;\n\n if (liquidityDelta == 0) {\n // disallow pokes for 0 liquidity positions\n if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n } else {\n self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n unchecked {\n feesOwed0 =\n FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n feesOwed1 =\n FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n }\n\n // update the position\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n using CustomRevert for bytes4;\n\n error SafeCastOverflow();\n\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint160\n function toUint160(uint256 x) internal pure returns (uint160 y) {\n y = uint160(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a uint128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint128\n function toUint128(uint256 x) internal pure returns (uint128 y) {\n y = uint128(x);\n if (x != y) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n /// @param x The int128 to be casted\n /// @return y The casted integer, now type uint128\n function toUint128(int128 x) internal pure returns (uint128 y) {\n if (x < 0) SafeCastOverflow.selector.revertWith();\n y = uint128(x);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param x The int256 to be downcasted\n /// @return y The downcasted integer, now type int128\n function toInt128(int256 x) internal pure returns (int128 y) {\n y = int128(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param x The uint256 to be casted\n /// @return y The casted integer, now type int256\n function toInt256(uint256 x) internal pure returns (int256 y) {\n y = int256(x);\n if (y < 0) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return The downcasted integer, now type int128\n function toInt128(uint256 x) internal pure returns (int128) {\n if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n return int128(int256(x));\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/StateLibrary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n /// @notice index of pools mapping in the PoolManager\n bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n /// @notice index of feeGrowthGlobal0X128 in Pool.State\n uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n /// @notice index of liquidity in Pool.State\n uint256 public constant LIQUIDITY_OFFSET = 3;\n\n /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n uint256 public constant TICKS_OFFSET = 4;\n\n /// @notice index of tickBitmap mapping in Pool.State\n uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n uint256 public constant POSITIONS_OFFSET = 6;\n\n /**\n * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n * @dev Corresponds to pools[poolId].slot0\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n * @return tick The current tick of the pool.\n * @return protocolFee The protocol fee of the pool.\n * @return lpFee The swap fee of the pool.\n */\n function getSlot0(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n bytes32 data = manager.extsload(stateSlot);\n\n // 24 bits |24bits|24bits |24 bits|160 bits\n // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n // ---------- | fee |protocolfee | tick | sqrtPriceX96\n assembly (\"memory-safe\") {\n // bottom 160 bits of data\n sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n // next 24 bits of data\n tick := signextend(2, shr(160, data))\n // next 24 bits of data\n protocolFee := and(shr(184, data), 0xFFFFFF)\n // last 24 bits of data\n lpFee := and(shr(208, data), 0xFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the tick information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve information for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n )\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // read all 3 words of the TickInfo struct\n bytes32[] memory data = manager.extsload(slot, 3);\n assembly (\"memory-safe\") {\n let firstWord := mload(add(data, 32))\n liquidityNet := sar(128, firstWord)\n liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n feeGrowthOutside0X128 := mload(add(data, 64))\n feeGrowthOutside1X128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve liquidity for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n */\n function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint128 liquidityGross, int128 liquidityNet)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n bytes32 value = manager.extsload(slot);\n assembly (\"memory-safe\") {\n liquidityNet := sar(128, value)\n liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the fee growth outside a tick range of a pool\n * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve fee growth for.\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // offset by 1 word, since the first word is liquidityGross + liquidityNet\n bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n assembly (\"memory-safe\") {\n feeGrowthOutside0X128 := mload(add(data, 32))\n feeGrowthOutside1X128 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves the global fee growth of a pool.\n * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return feeGrowthGlobal0 The global fee growth for token0.\n * @return feeGrowthGlobal1 The global fee growth for token1.\n * @dev Note that feeGrowthGlobal can be artificially inflated\n * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n */\n function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State, `uint256 feeGrowthGlobal0X128`\n bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n // read the 2 words of feeGrowthGlobal\n bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n assembly (\"memory-safe\") {\n feeGrowthGlobal0 := mload(add(data, 32))\n feeGrowthGlobal1 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves total the liquidity of a pool.\n * @dev Corresponds to pools[poolId].liquidity\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return liquidity The liquidity of the pool.\n */\n function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `uint128 liquidity`\n bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Retrieves the tick bitmap of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].tickBitmap[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve the bitmap for.\n * @return tickBitmap The bitmap of the tick.\n */\n function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n internal\n view\n returns (uint256 tickBitmap)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n tickBitmap = uint256(manager.extsload(slot));\n }\n\n /**\n * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param poolId The ID of the pool.\n * @param owner The owner of the liquidity position.\n * @param tickLower The lower tick of the liquidity range.\n * @param tickUpper The upper tick of the liquidity range.\n * @param salt The bytes32 randomness to further distinguish position state.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(\n IPoolManager manager,\n PoolId poolId,\n address owner,\n int24 tickLower,\n int24 tickUpper,\n bytes32 salt\n ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n }\n\n /**\n * @notice Retrieves the position information of a pool at a specific position ID.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n // read all 3 words of the Position.State struct\n bytes32[] memory data = manager.extsload(slot, 3);\n\n assembly (\"memory-safe\") {\n liquidity := mload(add(data, 32))\n feeGrowthInside0LastX128 := mload(add(data, 64))\n feeGrowthInside1LastX128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity of a position.\n * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n */\n function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Calculate the fee growth inside a tick range of a pool\n * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tickLower The lower tick of the range.\n * @param tickUpper The upper tick of the range.\n * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n */\n function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n internal\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n {\n (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickLower);\n (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickUpper);\n (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n unchecked {\n if (tickCurrent < tickLower) {\n feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n } else if (tickCurrent >= tickUpper) {\n feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n }\n }\n }\n\n function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n }\n\n function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int24 => TickInfo) ticks`\n bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n // slot key of the tick key: `pools[poolId].ticks[tick]\n return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n }\n\n function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(bytes32 => Position.State) positions;`\n bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n // slot of the mapping key: `pools[poolId].positions[positionId]\n return keccak256(abi.encodePacked(positionId, positionMapping));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BalanceDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n assembly (\"memory-safe\") {\n balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := add(a0, b0)\n res1 := add(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := sub(a0, b0)\n res1 := sub(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n /// @notice A BalanceDelta of 0\n BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n assembly (\"memory-safe\") {\n _amount0 := sar(128, balanceDelta)\n }\n }\n\n function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n assembly (\"memory-safe\") {\n _amount1 := signextend(15, balanceDelta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BeforeSwapDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n pure\n returns (BeforeSwapDelta beforeSwapDelta)\n{\n assembly (\"memory-safe\") {\n beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n /// @notice A BeforeSwapDelta of 0\n BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap\n function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n assembly (\"memory-safe\") {\n deltaSpecified := sar(128, delta)\n }\n }\n\n /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap and afterSwap\n function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n assembly (\"memory-safe\") {\n deltaUnspecified := signextend(15, delta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/Currency.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n error NativeTransferFailed();\n\n /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n error ERC20TransferFailed();\n\n /// @notice A constant to represent the native currency\n Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n function transfer(Currency currency, address to, uint256 amount) internal {\n // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n // modified custom error selectors\n\n bool success;\n if (currency.isAddressZero()) {\n assembly (\"memory-safe\") {\n // Transfer the ETH and revert if it fails.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n // revert with NativeTransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n }\n } else {\n assembly (\"memory-safe\") {\n // Get a pointer to some free memory.\n let fmp := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n success :=\n and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), currency, 0, fmp, 68, 0, 32)\n )\n\n // Now clean the memory we used\n mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n }\n // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(\n Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n );\n }\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return address(this).balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n }\n }\n\n function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return owner.balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n }\n }\n\n function isAddressZero(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n }\n\n function toId(Currency currency) internal pure returns (uint256) {\n return uint160(Currency.unwrap(currency));\n }\n\n // If the upper 12 bytes are non-zero, they will be zero-ed out\n // Therefore, fromId() and toId() are not inverses of each other\n function fromId(uint256 id) internal pure returns (Currency) {\n return Currency.wrap(address(uint160(id)));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolId.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n assembly (\"memory-safe\") {\n // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n poolId := keccak256(poolKey, 0xa0)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolKey.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n /// @notice The lower currency of the pool, sorted numerically\n Currency currency0;\n /// @notice The higher currency of the pool, sorted numerically\n Currency currency1;\n /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n uint24 fee;\n /// @notice Ticks that involve positions must be a multiple of tick spacing\n int24 tickSpacing;\n /// @notice The hooks of the pool\n IHooks hooks;\n}\n" + }, + "@uniswap/v4-core/src/types/PoolOperation.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // how to modify the liquidity\n int256 liquidityDelta;\n // a value to set if you want unique liquidity positions at the same range\n bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n /// Whether to swap token0 for token1 or vice versa\n bool zeroForOne;\n /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n int256 amountSpecified;\n /// The sqrt price at which, if reached, the swap will stop executing\n uint160 sqrtPriceLimitX96;\n}\n" + }, + "contracts/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\n}\n" + }, + "contracts/interfaces/defi/IAerodromePool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAerodromePool\n * @notice Defines the basic interface for an Aerodrome Pool.\n */\ninterface IAerodromePool {\n function lastObservation() external view returns (uint256, uint256, uint256);\n function observationLength() external view returns (uint256 );\n\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/ILenderCommitmentGroup_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V3 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n\n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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/IUniswapV4Pool.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 IUniswapV4Pool 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/interfaces/uniswapv4/IImmutableState.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n /// @notice The Uniswap v4 PoolManager contract\n function poolManager() external view returns (IPoolManager);\n}" + }, + "contracts/interfaces/uniswapv4/IStateView.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {PoolId} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {Position} from \"@uniswap/v4-core/src/libraries/Position.sol\";\nimport {IImmutableState} from \"./IImmutableState.sol\";\n\n/// @title IStateView\n/// @notice Interface for the StateView contract\ninterface IStateView is IImmutableState {\n /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n /// @dev Corresponds to pools[poolId].slot0\n /// @param poolId The ID of the pool.\n /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n /// @return tick The current tick of the pool.\n /// @return protocolFee The protocol fee of the pool.\n /// @return lpFee The swap fee of the pool.\n function getSlot0(PoolId poolId)\n external\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);\n\n /// @notice Retrieves the tick information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve information for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickInfo(PoolId poolId, int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n );\n\n /// @notice Retrieves the liquidity information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve liquidity for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function getTickLiquidity(PoolId poolId, int24 tick)\n external\n view\n returns (uint128 liquidityGross, int128 liquidityNet);\n\n /// @notice Retrieves the fee growth outside a tick range of a pool\n /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve fee growth for.\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickFeeGrowthOutside(PoolId poolId, int24 tick)\n external\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128);\n\n /// @notice Retrieves the global fee growth of a pool.\n /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n /// @param poolId The ID of the pool.\n /// @return feeGrowthGlobal0 The global fee growth for token0.\n /// @return feeGrowthGlobal1 The global fee growth for token1.\n function getFeeGrowthGlobals(PoolId poolId)\n external\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1);\n\n /// @notice Retrieves the total liquidity of a pool.\n /// @dev Corresponds to pools[poolId].liquidity\n /// @param poolId The ID of the pool.\n /// @return liquidity The liquidity of the pool.\n function getLiquidity(PoolId poolId) external view returns (uint128 liquidity);\n\n /// @notice Retrieves the tick bitmap of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].tickBitmap[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve the bitmap for.\n /// @return tickBitmap The bitmap of the tick.\n function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap);\n\n /// @notice Retrieves the position info without needing to calculate the `positionId`.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param owner The owner of the liquidity position.\n /// @param tickLower The lower tick of the liquidity range.\n /// @param tickUpper The upper tick of the liquidity range.\n /// @param salt The bytes32 randomness to further distinguish position state.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the position information of a pool at a specific position ID.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, bytes32 positionId)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the liquidity of a position.\n /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity);\n\n /// @notice Calculate the fee growth inside a tick range of a pool\n /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside\n /// @param poolId The ID of the pool.\n /// @param tickLower The lower tick of the range.\n /// @param tickUpper The upper tick of the range.\n /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper)\n external\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _priceAdapterAddress Address for the pool price adapter\n * @param _priceAdapterRoute Encoded roue for the price adapter \n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V3.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _priceAdapterAddress,\n _priceAdapterRoute\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\n\n} " + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.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 import \"../../../interfaces/IPriceAdapter.sol\";\n\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\nimport {FixedPointQ96} from \"../../../libraries/FixedPointQ96.sol\";\n\n\n\nimport \"../../../libraries/uniswap/TickMath.sol\";\nimport \"../../../libraries/uniswap/FixedPoint96.sol\";\nimport \"../../../libraries/uniswap/FullMath.sol\";\n \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\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_Pool_V3 is\n ILenderCommitmentGroup_V3,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\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 priceAdapter;\n \n \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 bytes32 public priceRouteHash;\n \n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW \n\n\n uint256 public lastUnpausedAt;\n bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n\n\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n\n \n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _priceAdapterRoute Route configuration for the principal/collateral oracle.\n\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n address _priceAdapter, \n \n bytes calldata _priceAdapterRoute\n\n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \n\n \n priceAdapter = _priceAdapter ;\n \n //internally this does checks and might revert \n // we register the price route with the adapter and save it locally \n priceRouteHash = IPriceAdapter( priceAdapter ).registerPriceRoute(\n _priceAdapterRoute\n );\n\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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\n \n // principalPerCollateralAmount\n uint256 priceRatioQ96 = IPriceAdapter( priceAdapter )\n .getPriceRatioQ96(priceRouteHash);\n \n \n \n\n return\n getRequiredCollateral(\n principalAmount,\n priceRatioQ96 // principalPerCollateralAmount \n );\n }\n\n \n \n\n /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 \n \n ) internal view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n FixedPointQ96.Q96,\n _maxPrincipalPerCollateralAmountQ96,\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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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 \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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Sets the delay time for withdrawing shares. 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 , \"WD\");\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"FDM\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"IC\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\");\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAerodrome.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAerodromePool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n import {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n\n\ncontract PriceAdapterAerodrome is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n // hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n // store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \n\n\n if (twapInterval == 0 ){\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\n\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \n }\n\n\n \n // Get two observations: current and one from twapInterval seconds ago\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = 0; // current\n secondsAgos[1] = twapInterval + 0 ; // oldest\n \n\n // Fetch observations\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\n\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\n\n // Calculate time-weighted average reserves\n uint256 timeElapsed = timestamp0 - timestamp1 ;\n require(timeElapsed > 0, \"Invalid time elapsed\");\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\n \n \n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\n\n\n\n\n }\n\n\n\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n\n }\n\n\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/*\n\n see https://docs.uniswap.org/contracts/v4/deployments \n\n\n https://docs.uniswap.org/contracts/v4/guides/read-pool-state\n\n\n\n*/\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\n\nimport {IStateView} from \"../interfaces/uniswapv4/IStateView.sol\";\n \nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\n\n\n\n\ncontract PriceAdapterUniswapV4 is\n IPriceAdapter\n\n{ \n\n \n\n using PoolIdLibrary for PoolKey;\n\n IPoolManager public immutable poolManager;\n\n\n using StateLibrary for IPoolManager;\n // address immutable POOL_MANAGER_V4; \n\n\n // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet \n //address immutable UNISWAP_V4_STATE_VIEW; \n\n struct PoolRoute {\n PoolId pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n \n\n constructor(IPoolManager _poolManager) {\n poolManager = _poolManager;\n }\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n function getPoolState(PoolId poolId) internal view returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint24 protocolFee,\n uint24 lpFee\n ) {\n return poolManager.getSlot0(poolId);\n }\n\n\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(PoolId poolId, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , ) = getPoolState(poolId);\n } else {\n\n revert(\"twap price not impl \");\n\n \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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 bf37eb53d24aa820aabdcaf228b896a232aff711 Mon Sep 17 00:00:00 2001 From: andy Date: Fri, 21 Nov 2025 14:31:02 -0500 Subject: [PATCH 35/46] uniswap v2 adapter draft --- .../interfaces/uniswap/IUniswapV2Pair.sol | 52 ++++ .../price_adapters/PriceAdapterUniswapV2.sol | 222 ++++++++++++++++++ .../deploy/pricing/price_adapter_aerodrome.ts | 9 +- .../pricing/price_adapter_uniswap_v2.ts | 45 ++++ .../pricing/price_adapter_uniswap_v3.ts | 47 ++++ .../PriceAdapter_Aerodrome_Test.sol | 35 +++ 6 files changed, 408 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/contracts/interfaces/uniswap/IUniswapV2Pair.sol create mode 100644 packages/contracts/contracts/price_adapters/PriceAdapterUniswapV2.sol create mode 100644 packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts create mode 100644 packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts diff --git a/packages/contracts/contracts/interfaces/uniswap/IUniswapV2Pair.sol b/packages/contracts/contracts/interfaces/uniswap/IUniswapV2Pair.sol new file mode 100644 index 000000000..4080678b8 --- /dev/null +++ b/packages/contracts/contracts/interfaces/uniswap/IUniswapV2Pair.sol @@ -0,0 +1,52 @@ +pragma solidity >=0.8.0; + +interface IUniswapV2Pair { + event Approval(address indexed owner, address indexed spender, uint value); + event Transfer(address indexed from, address indexed to, uint value); + + function name() external pure returns (string memory); + function symbol() external pure returns (string memory); + function decimals() external pure returns (uint8); + function totalSupply() external view returns (uint); + function balanceOf(address owner) external view returns (uint); + function allowance(address owner, address spender) external view returns (uint); + + function approve(address spender, uint value) external returns (bool); + function transfer(address to, uint value) external returns (bool); + function transferFrom(address from, address to, uint value) external returns (bool); + + function DOMAIN_SEPARATOR() external view returns (bytes32); + function PERMIT_TYPEHASH() external pure returns (bytes32); + function nonces(address owner) external view returns (uint); + + function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; + + event Mint(address indexed sender, uint amount0, uint amount1); + event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); + event Swap( + address indexed sender, + uint amount0In, + uint amount1In, + uint amount0Out, + uint amount1Out, + address indexed to + ); + event Sync(uint112 reserve0, uint112 reserve1); + + function MINIMUM_LIQUIDITY() external pure returns (uint); + function factory() external view returns (address); + function token0() external view returns (address); + function token1() external view returns (address); + function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); + function price0CumulativeLast() external view returns (uint); + function price1CumulativeLast() external view returns (uint); + function kLast() external view returns (uint); + + function mint(address to) external returns (uint liquidity); + function burn(address to) external returns (uint amount0, uint amount1); + function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; + function skim(address to) external; + function sync() external; + + function initialize(address, address) external; +} diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV2.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV2.sol new file mode 100644 index 000000000..7e6d575a9 --- /dev/null +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV2.sol @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + + + +// Interfaces +import "../interfaces/IPriceAdapter.sol"; +import "../interfaces/uniswap/IUniswapV2Pair.sol"; + +import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; +import {FullMath} from "../libraries/uniswap/FullMath.sol"; +import {FixedPointMathLib} from "../libraries/erc4626/utils/FixedPointMathLib.sol"; + +/* + + UniswapV2 Price Adapter (compatible with Sushiswap and other V2 forks) + Uses reserves for current price + + + Cannot compute TWAP price as uniswapV2 doesnt provide historic data + +*/ + + +contract PriceAdapterUniswapV2 is + IPriceAdapter + +{ + + + + + + struct PoolRoute { + address pool; + bool zeroForOne; + uint32 twapInterval; + uint256 token0Decimals; + uint256 token1Decimals; + } + + + + + + + mapping(bytes32 => bytes) public priceRoutes; + + + + + /* Events */ + + event RouteRegistered(bytes32 hash, bytes route); + + + /* External Functions */ + + + function registerPriceRoute( + bytes memory route + ) external returns (bytes32 hash) { + + PoolRoute[] memory route_array = decodePoolRoutes( route ); + + // hash the route with keccak256 + bytes32 poolRouteHash = keccak256(route); + + // store the route by its hash in the priceRoutes mapping + priceRoutes[poolRouteHash] = route; + + emit RouteRegistered(poolRouteHash, route); + + return poolRouteHash; + } + + + + + + function getPriceRatioQ96( + bytes32 route + ) external view returns ( uint256 priceRatioQ96 ) { + + // lookup the route from the mapping + bytes memory routeData = priceRoutes[route]; + require(routeData.length > 0, "Route not found"); + + // decode the route + PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData); + + // start with Q96 = 1.0 in Q96 format + priceRatioQ96 = FixedPointQ96.Q96; + + // iterate through each pool and multiply prices + for (uint256 i = 0; i < poolRoutes.length; i++) { + uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]); + // multiply using Q96 arithmetic + priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96); + } + } + + + + // ------- + + + + function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) { + + encoded = abi.encode(routes); + + } + + + // validate the route for length, other restrictions + //must be length 1 or 2 + + function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { + + route_array = abi.decode(data, (PoolRoute[])); + + require(route_array.length == 1 || route_array.length == 2, "Route must have 1 or 2 pools"); + + } + + + + + // ------- + + + + function getUniswapPriceRatioForPool( + PoolRoute memory _poolRoute + ) internal view returns (uint256 priceRatioQ96) { + + // Get sqrtPriceX96 from UniswapV2 reserves + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRoute.pool, + _poolRoute.twapInterval + ); + + // Convert sqrtPriceX96 to priceQ96 + // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format + priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96); + + // If we need the inverse (token0 in terms of token1), invert + bool invert = !_poolRoute.zeroForOne; + if (invert) { + // To invert a Q96 number: (Q96 * Q96) / value + priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96); + } + } + + function getSqrtTwapX96(address uniswapV2Pool, uint32 twapInterval) + internal + view + returns (uint160 sqrtPriceX96) + { + IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pool); + + if (twapInterval == 0) { + // Use current reserves for immediate price + (uint112 reserve0, uint112 reserve1, ) = pair.getReserves(); + sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1)); + } else { + // For TWAP, use cumulative prices + // Note: In a single transaction, we can only get the current cumulative prices + // This requires storing historical cumulative prices on-chain for proper TWAP calculation + // For now, we use current reserves as a fallback + (uint112 reserve0, uint112 reserve1, ) = pair.getReserves(); + sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1)); + } + } + + function getSqrtPriceX96FromReserves(uint256 reserve0, uint256 reserve1) + internal + pure + returns (uint160 sqrtPriceX96) + { + // Calculate sqrt(reserve1 / reserve0) * 2^96 + // This represents the price of token0 in terms of token1 + + require(reserve0 > 0, "Reserve0 cannot be zero"); + require(reserve1 > 0, "Reserve1 cannot be zero"); + + uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0); + uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1); + + sqrtPriceX96 = uint160( + FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0) + ); + } + + function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceQ96) + { + // sqrtPriceX96^2 / 2^96 = priceQ96 + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96); + } + + + + + + + + + + + + + + + + + + +} diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 9edf10295..3a9c62340 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -16,8 +16,13 @@ const deployFn: DeployFunction = async (hre) => { - // need to add a delay , wait here ! - // await tx.wait(1) // wait one block + hre.log('FixedPointQ96 library deployed at:' ) + hre.log(FixedPointQ96.address) + + // Wait for one block confirmation + if (FixedPointQ96.receipt) { + await hre.ethers.provider.waitForTransaction(FixedPointQ96.receipt.transactionHash, 1) + } diff --git a/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts b/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts new file mode 100644 index 000000000..d3ef5f77a --- /dev/null +++ b/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts @@ -0,0 +1,45 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + + + + const { deployer } = await hre.getNamedAccounts() + + // Deploy FixedPointQ96 library first + const FixedPointQ96 = await hre.deployments.deploy('FixedPointQ96', { + from: deployer, + }) + + hre.log('FixedPointQ96 library deployed at:' ) + hre.log( FixedPointQ96.address) + + + + // need to add a delay , wait here ! + // await tx.wait(1) // wait one block + + + const PriceAdapterUniswapV2 = await hre.deployments.deploy('PriceAdapterUniswapV2', { + from: deployer, + libraries: { + FixedPointQ96: FixedPointQ96.address, + }, + }) + + hre.log('PriceAdapterUniswapV2 deployed at:' ) + hre.log( PriceAdapterUniswapV2.address) + + +} + +// tags and deployment +deployFn.id = 'price-adapter-uniswap-v2:deploy' +deployFn.tags = ['teller-v2', 'price-adapter-uniswap-v2:deploy'] +deployFn.dependencies = [] + +deployFn.skip = async (hre) => { + return !hre.network.live || ![ 'base', ].includes(hre.network.name) + } + +export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts new file mode 100644 index 000000000..890d6949f --- /dev/null +++ b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts @@ -0,0 +1,47 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + + + + const { deployer } = await hre.getNamedAccounts() + + // Deploy FixedPointQ96 library first + const FixedPointQ96 = await hre.deployments.deploy('FixedPointQ96', { + from: deployer, + }) + + hre.log('FixedPointQ96 library deployed at:' ) + hre.log( FixedPointQ96.address) + + + + // need to add a delay , wait here ! + // await tx.wait(1) // wait one block + + + + // Deploy PriceAdapterAerodrome with linked library + const PriceAdapterUniswapV3 = await hre.deployments.deploy('PriceAdapterUniswapV3', { + from: deployer, + libraries: { + FixedPointQ96: FixedPointQ96.address, + }, + }) + + hre.log('PriceAdapterUniswapV3 deployed at:' ) + hre.log( PriceAdapterUniswapV3.address) + + +} + +// tags and deployment +deployFn.id = 'price-adapter-uniswap-v3:deploy' +deployFn.tags = ['teller-v2', 'price-adapter-uniswap-v3:deploy'] +deployFn.dependencies = [] + +deployFn.skip = async (hre) => { + return !hre.network.live || ![ 'base', ].includes(hre.network.name) + } + +export default deployFn \ No newline at end of file diff --git a/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol index 36d769886..de56d8000 100644 --- a/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol +++ b/packages/contracts/tests_fork/PriceAdapter_Aerodrome_Test.sol @@ -241,6 +241,41 @@ contract PoolsV3_Aerodrome_Fork_Test is Test { console.log("Expected ~1e18 (should be close)"); } + function test_two_hop_route_twap() public { + // Create a two-hop route using the same pool twice (just for testing) + PriceAdapterAerodrome.PoolRoute[] memory routes = new PriceAdapterAerodrome.PoolRoute[](2); + routes[0] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: true, + twapInterval: 5, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = PriceAdapterAerodrome.PoolRoute({ + pool: AERODROME_POOL, + zeroForOne: false, // Go back + twapInterval: 5, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + + assertTrue(priceRatioQ96 > 0, "Two-hop price should be greater than 0"); + + // This should be close to 2^96 (1.0) since we go there and back + uint256 priceQ96Divisor = 2 ** 96; + uint256 priceScaled = (priceRatioQ96 * 1e18) / priceQ96Divisor; + + console.log("Two-hop Price Q96:", priceRatioQ96); + console.log("Two-hop Price (scaled by 1e18):", priceScaled); + console.log("Expected ~1e18 (should be close)"); + } + + /** * @notice Test that decoding validates route length */ From e55587ede4e9d3a8ecc15149e0e1bb25b2b5d125 Mon Sep 17 00:00:00 2001 From: andy Date: Fri, 21 Nov 2025 14:37:05 -0500 Subject: [PATCH 36/46] deploy script --- .../price_adapters/PriceAdapterUniswapV3.sol | 3 ++ .../deploy/pricing/price_adapter_aerodrome.ts | 5 +-- .../pricing/price_adapter_uniswap_v2.ts | 45 ------------------- .../pricing/price_adapter_uniswap_v3.ts | 7 ++- 4 files changed, 9 insertions(+), 51 deletions(-) delete mode 100644 packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol index 98ab5ca2e..cbc81501e 100644 --- a/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol +++ b/packages/contracts/contracts/price_adapters/PriceAdapterUniswapV3.sol @@ -59,6 +59,9 @@ contract PriceAdapterUniswapV3 is PoolRoute[] memory route_array = decodePoolRoutes( route ); + + require( route_array.length ==1 || route_array.length ==2, "invalid route length" ); + // hash the route with keccak256 bytes32 poolRouteHash = keccak256(route); diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 3a9c62340..592a56d37 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -14,10 +14,7 @@ const deployFn: DeployFunction = async (hre) => { hre.log('FixedPointQ96 library deployed at:' ) hre.log( FixedPointQ96.address) - - - hre.log('FixedPointQ96 library deployed at:' ) - hre.log(FixedPointQ96.address) + // Wait for one block confirmation if (FixedPointQ96.receipt) { diff --git a/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts b/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts deleted file mode 100644 index d3ef5f77a..000000000 --- a/packages/contracts/deploy/pricing/price_adapter_uniswap_v2.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { DeployFunction } from 'hardhat-deploy/dist/types' - -const deployFn: DeployFunction = async (hre) => { - - - - const { deployer } = await hre.getNamedAccounts() - - // Deploy FixedPointQ96 library first - const FixedPointQ96 = await hre.deployments.deploy('FixedPointQ96', { - from: deployer, - }) - - hre.log('FixedPointQ96 library deployed at:' ) - hre.log( FixedPointQ96.address) - - - - // need to add a delay , wait here ! - // await tx.wait(1) // wait one block - - - const PriceAdapterUniswapV2 = await hre.deployments.deploy('PriceAdapterUniswapV2', { - from: deployer, - libraries: { - FixedPointQ96: FixedPointQ96.address, - }, - }) - - hre.log('PriceAdapterUniswapV2 deployed at:' ) - hre.log( PriceAdapterUniswapV2.address) - - -} - -// tags and deployment -deployFn.id = 'price-adapter-uniswap-v2:deploy' -deployFn.tags = ['teller-v2', 'price-adapter-uniswap-v2:deploy'] -deployFn.dependencies = [] - -deployFn.skip = async (hre) => { - return !hre.network.live || ![ 'base', ].includes(hre.network.name) - } - -export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts index 890d6949f..7bf21f326 100644 --- a/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts +++ b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts @@ -16,8 +16,11 @@ const deployFn: DeployFunction = async (hre) => { - // need to add a delay , wait here ! - // await tx.wait(1) // wait one block + + // Wait for one block confirmation + if (FixedPointQ96.receipt) { + await hre.ethers.provider.waitForTransaction(FixedPointQ96.receipt.transactionHash, 1) + } From 86ce047b2f85469264cde3c672e50c59b1a04e37 Mon Sep 17 00:00:00 2001 From: andy Date: Fri, 21 Nov 2025 14:38:14 -0500 Subject: [PATCH 37/46] deployed univ3 price adapter --- .../deploy/pricing/price_adapter_aerodrome.ts | 8 +- .../pricing/price_adapter_uniswap_v3.ts | 8 +- .../base/PriceAdapterUniswapV3.json | 239 ++++++++++++++++++ .../b260a2753d21b48077cb0d9db054a12f.json | 77 ++++++ 4 files changed, 318 insertions(+), 14 deletions(-) create mode 100644 packages/contracts/deployments/base/PriceAdapterUniswapV3.json create mode 100644 packages/contracts/deployments/base/solcInputs/b260a2753d21b48077cb0d9db054a12f.json diff --git a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts index 592a56d37..4475175fe 100644 --- a/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts +++ b/packages/contracts/deploy/pricing/price_adapter_aerodrome.ts @@ -14,13 +14,7 @@ const deployFn: DeployFunction = async (hre) => { hre.log('FixedPointQ96 library deployed at:' ) hre.log( FixedPointQ96.address) - - - // Wait for one block confirmation - if (FixedPointQ96.receipt) { - await hre.ethers.provider.waitForTransaction(FixedPointQ96.receipt.transactionHash, 1) - } - + // Deploy PriceAdapterAerodrome with linked library diff --git a/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts index 7bf21f326..69ca4fe45 100644 --- a/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts +++ b/packages/contracts/deploy/pricing/price_adapter_uniswap_v3.ts @@ -16,13 +16,7 @@ const deployFn: DeployFunction = async (hre) => { - - // Wait for one block confirmation - if (FixedPointQ96.receipt) { - await hre.ethers.provider.waitForTransaction(FixedPointQ96.receipt.transactionHash, 1) - } - - + // Deploy PriceAdapterAerodrome with linked library const PriceAdapterUniswapV3 = await hre.deployments.deploy('PriceAdapterUniswapV3', { diff --git a/packages/contracts/deployments/base/PriceAdapterUniswapV3.json b/packages/contracts/deployments/base/PriceAdapterUniswapV3.json new file mode 100644 index 000000000..4de7096f6 --- /dev/null +++ b/packages/contracts/deployments/base/PriceAdapterUniswapV3.json @@ -0,0 +1,239 @@ +{ + "address": "0x39Ac6A68DEe355F56dC08d641458ca58A4EE24d0", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterUniswapV3.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterUniswapV3.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x5f4ed7c0177bf5ee619e093ac8d7e8452deea65dd803101e762b2007446392bd", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x39Ac6A68DEe355F56dC08d641458ca58A4EE24d0", + "transactionIndex": 87, + "gasUsed": "1244673", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x44448c28dc67be090e4cc63a23d8d06008ae52070c52061515565440dbb6053f", + "transactionHash": "0x5f4ed7c0177bf5ee619e093ac8d7e8452deea65dd803101e762b2007446392bd", + "logs": [], + "blockNumber": 38482267, + "cumulativeGasUsed": "11065968", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "b260a2753d21b48077cb0d9db054a12f", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterUniswapV3.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterUniswapV3.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterUniswapV3.sol\":\"PriceAdapterUniswapV3\"},\"evmVersion\":\"shanghai\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"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/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"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\"},\"contracts/price_adapters/PriceAdapterUniswapV3.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n \\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/uniswap/IUniswapV3Pool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n\\n/*\\n\\n This is (typically) compatible with Sushiswap and Aerodrome \\n\\n*/\\n\\n\\ncontract PriceAdapterUniswapV3 is\\n IPriceAdapter\\n\\n{\\n \\n\\n\\n\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n\\n\\n \\n mapping(bytes32 => bytes) public priceRoutes; \\n \\n \\n\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n \\n\\n /* External Functions */\\n \\n \\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n\\n require( route_array.length ==1 || route_array.length ==2, \\\"invalid route length\\\" );\\n\\n \\t\\t// hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n \\t\\t// store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n \\n\\n\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n\\n\\n // -------\\n\\n\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n\\n // validate the route for length, other restrictions\\n //must be length 1 or 2\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n\\n\\n\\n // -------\\n\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n}\\n\",\"keccak256\":\"0x99c207155e2e37d6394c60a381f8989a71c52bd313d7544f1da6061860b7d455\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561000f575f80fd5b506115878061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610c46565b6100e9565b6040516100799190610ca0565b60405180910390f35b610095610090366004610c46565b610180565b604051908152602001610079565b61006c6100b1366004610d78565b610330565b6100956100c4366004610e63565b610359565b6100dc6100d7366004610e63565b61041d565b6040516100799190610ef2565b5f602081905290815260409020805461010190610f70565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610f70565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610f70565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610f70565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a8261041d565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610fa8565b6020026020010151610497565b604051631c0e258560e21b8152600481018790526024810182905290915073353F415320f6B5351e5516951F6eCb636CFcB4B990637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610fbc565b945050600101610275565b505050919050565b6060816040516020016103439190610ef2565b6040516020818303038152906040529050919050565b5f806103648361041d565b9050805160011480610377575080516002145b6103ba5760405162461bcd60e51b81526020600482015260146024820152730d2dcecc2d8d2c840e4deeae8ca40d8cadccee8d60631b6044820152606401610257565b82516020808501919091205f8181529182905260409091206103dc858261101f565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d4818560405161040e9291906110df565b60405180910390a19392505050565b60608180602001905181019061043391906110ff565b9050805160011480610446575080516002145b6104925760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f806104aa835f015184604001516104dd565b90506104b5816106ad565b60208401519092501580156104d6576104d3600160601b80856106c2565b92505b5050919050565b5f8163ffffffff165f0361055a57826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610527573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061054b91906111ea565b509495506106a7945050505050565b6040805160028082526060820183525f92602083019080368337019050509050610585836001611296565b815f8151811061059757610597610fa8565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106105c6576105c6610fa8565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd906106099085906004016112ba565b5f60405180830381865afa158015610623573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261064a9190810190611373565b5090506106a28460030b825f8151811061066657610666610fa8565b60200260200101518360018151811061068157610681610fa8565b60200260200101516106939190611437565b61069d9190611478565b610833565b925050505b92915050565b5f6106a76001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f036106f6575f84116106eb575f80fd5b50829004905061082c565b808411610701575f80fd5b5f848688098084039381119092039190505f85610720811960016114b4565b16958690049593849004935f81900304600101905061073f81846114c7565b909317925f61074f8760036114c7565b600218905061075e81886114c7565b6107699060026114de565b61077390826114c7565b905061077f81886114c7565b61078a9060026114de565b61079490826114c7565b90506107a081886114c7565b6107ab9060026114de565b6107b590826114c7565b90506107c181886114c7565b6107cc9060026114de565b6107d690826114c7565b90506107e281886114c7565b6107ed9060026114de565b6107f790826114c7565b905061080381886114c7565b61080e9060026114de565b61081890826114c7565b905061082481866114c7565b955050505050505b9392505050565b5f805f8360020b12610848578260020b610855565b8260020b610855906114f1565b9050610864620d89e71961150b565b62ffffff1681111561089c5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610257565b5f816001165f036108b157600160801b6108c3565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156109025760806108fd826ffff97272373d413259a46990580e213a6114c7565b901c90505b600482161561092c576080610927826ffff2e50f5f656932ef12357cf3c7fdcc6114c7565b901c90505b6008821615610956576080610951826fffe5caca7e10e4e61c3624eaa0941cd06114c7565b901c90505b601082161561098057608061097b826fffcb9843d60f6159c9db58835c9266446114c7565b901c90505b60208216156109aa5760806109a5826fff973b41fa98c081472e6896dfb254c06114c7565b901c90505b60408216156109d45760806109cf826fff2ea16466c96a3843ec78b326b528616114c7565b901c90505b60808216156109fe5760806109f9826ffe5dee046a99a2a811c461f1969c30536114c7565b901c90505b610100821615610a29576080610a24826ffcbe86c7900a88aedcffc83b479aa3a46114c7565b901c90505b610200821615610a54576080610a4f826ff987a7253ac413176f2b074cf7815e546114c7565b901c90505b610400821615610a7f576080610a7a826ff3392b0822b70005940c7a398e4b70f36114c7565b901c90505b610800821615610aaa576080610aa5826fe7159475a2c29b7443b29c7fa6e889d96114c7565b901c90505b611000821615610ad5576080610ad0826fd097f3bdfd2022b8845ad8f792aa58256114c7565b901c90505b612000821615610b00576080610afb826fa9f746462d870fdf8a65dc1f90e061e56114c7565b901c90505b614000821615610b2b576080610b26826f70d869a156d2a1b890bb3df62baf32f76114c7565b901c90505b618000821615610b56576080610b51826f31be135f97d08fd981231505542fcfa66114c7565b901c90505b62010000821615610b82576080610b7d826f09aa508b5b7a84e1c677de54f3e99bc96114c7565b901c90505b62020000821615610bad576080610ba8826e5d6af8dedb81196699c329225ee6046114c7565b901c90505b62040000821615610bd7576080610bd2826d2216e584f5fa1ea926041bedfe986114c7565b901c90505b62080000821615610bff576080610bfa826b048a170391f7dc42444e8fa26114c7565b901c90505b5f8460020b1315610c1857610c15815f1961152b565b90505b610c276401000000008261153e565b15610c33576001610c35565b5f5b6104d39060ff16602083901c6114b4565b5f60208284031215610c56575f80fd5b5035919050565b5f81518084525f5b81811015610c8157602081850181015186830182015201610c65565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61082c6020830184610c5d565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610ce957610ce9610cb2565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d1857610d18610cb2565b604052919050565b5f67ffffffffffffffff821115610d3957610d39610cb2565b5060051b60200190565b6001600160a01b0381168114610d57575f80fd5b50565b8015158114610d57575f80fd5b63ffffffff81168114610d57575f80fd5b5f6020808385031215610d89575f80fd5b823567ffffffffffffffff811115610d9f575f80fd5b8301601f81018513610daf575f80fd5b8035610dc2610dbd82610d20565b610cef565b81815260a09182028301840191848201919088841115610de0575f80fd5b938501935b83851015610e575780858a031215610dfb575f80fd5b610e03610cc6565b8535610e0e81610d43565b815285870135610e1d81610d5a565b81880152604086810135610e3081610d67565b90820152606086810135908201526080808701359082015283529384019391850191610de5565b50979650505050505050565b5f6020808385031215610e74575f80fd5b823567ffffffffffffffff80821115610e8b575f80fd5b818501915085601f830112610e9e575f80fd5b813581811115610eb057610eb0610cb2565b610ec2601f8201601f19168501610cef565b91508082528684828501011115610ed7575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610f6357815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610f0e565b5091979650505050505050565b600181811c90821680610f8457607f821691505b602082108103610fa257634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610fcc575f80fd5b5051919050565b601f82111561101a57805f5260205f20601f840160051c81016020851015610ff85750805b601f840160051c820191505b81811015611017575f8155600101611004565b50505b505050565b815167ffffffffffffffff81111561103957611039610cb2565b61104d816110478454610f70565b84610fd3565b602080601f831160018114611080575f84156110695750858301515b5f19600386901b1c1916600185901b1785556110d7565b5f85815260208120601f198616915b828110156110ae5788860151825594840194600190910190840161108f565b50858210156110cb57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f6110f76040830184610c5d565b949350505050565b5f6020808385031215611110575f80fd5b825167ffffffffffffffff811115611126575f80fd5b8301601f81018513611136575f80fd5b8051611144610dbd82610d20565b81815260a09182028301840191848201919088841115611162575f80fd5b938501935b83851015610e575780858a03121561117d575f80fd5b611185610cc6565b855161119081610d43565b81528587015161119f81610d5a565b818801526040868101516111b281610d67565b90820152606086810151908201526080808701519082015283529384019391850191611167565b805161ffff81168114610492575f80fd5b5f805f805f805f60e0888a031215611200575f80fd5b875161120b81610d43565b8097505060208801518060020b8114611222575f80fd5b9550611230604089016111d9565b945061123e606089016111d9565b935061124c608089016111d9565b925060a088015160ff81168114611261575f80fd5b60c089015190925061127281610d5a565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b63ffffffff8181168382160190808211156112b3576112b3611282565b5092915050565b602080825282518282018190525f9190848201906040850190845b818110156112f757835163ffffffff16835292840192918401916001016112d5565b50909695505050505050565b5f82601f830112611312575f80fd5b81516020611322610dbd83610d20565b8083825260208201915060208460051b870101935086841115611343575f80fd5b602086015b8481101561136857805161135b81610d43565b8352918301918301611348565b509695505050505050565b5f8060408385031215611384575f80fd5b825167ffffffffffffffff8082111561139b575f80fd5b818501915085601f8301126113ae575f80fd5b815160206113be610dbd83610d20565b82815260059290921b840181019181810190898411156113dc575f80fd5b948201945b838610156114085785518060060b81146113f9575f80fd5b825294820194908201906113e1565b91880151919650909350505080821115611420575f80fd5b5061142d85828601611303565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156106a7576106a7611282565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b8061148e5761148e611464565b667fffffffffffff1982145f19821416156114ab576114ab611282565b90059392505050565b808201808211156106a7576106a7611282565b80820281158282048414176106a7576106a7611282565b818103818111156106a7576106a7611282565b5f600160ff1b820161150557611505611282565b505f0390565b5f8160020b627fffff19810361152357611523611282565b5f0392915050565b5f8261153957611539611464565b500490565b5f8261154c5761154c611464565b50069056fea26469706673582212204579e3d4c88f16d070acd2de879f85800ce2ed9254a6001866db38ff34eec26464736f6c63430008180033", + "deployedBytecode": "0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c806327e30db114610059578063506fbf1f1461008257806395240738146100a3578063bd9644a7146100b6578063dd19ebd0146100c9575b5f80fd5b61006c610067366004610c46565b6100e9565b6040516100799190610ca0565b60405180910390f35b610095610090366004610c46565b610180565b604051908152602001610079565b61006c6100b1366004610d78565b610330565b6100956100c4366004610e63565b610359565b6100dc6100d7366004610e63565b61041d565b6040516100799190610ef2565b5f602081905290815260409020805461010190610f70565b80601f016020809104026020016040519081016040528092919081815260200182805461012d90610f70565b80156101785780601f1061014f57610100808354040283529160200191610178565b820191905f5260205f20905b81548152906001019060200180831161015b57829003601f168201915b505050505081565b5f818152602081905260408120805482919061019b90610f70565b80601f01602080910402602001604051908101604052809291908181526020018280546101c790610f70565b80156102125780601f106101e957610100808354040283529160200191610212565b820191905f5260205f20905b8154815290600101906020018083116101f557829003601f168201915b505050505090505f8151116102605760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b5f61026a8261041d565b9050600160601b92505f5b8151811015610328575f6102a183838151811061029457610294610fa8565b6020026020010151610497565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af41580156102f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031d9190610fbc565b945050600101610275565b505050919050565b6060816040516020016103439190610ef2565b6040516020818303038152906040529050919050565b5f806103648361041d565b9050805160011480610377575080516002145b6103ba5760405162461bcd60e51b81526020600482015260146024820152730d2dcecc2d8d2c840e4deeae8ca40d8cadccee8d60631b6044820152606401610257565b82516020808501919091205f8181529182905260409091206103dc858261101f565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d4818560405161040e9291906110df565b60405180910390a19392505050565b60608180602001905181019061043391906110ff565b9050805160011480610446575080516002145b6104925760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610257565b919050565b5f806104aa835f015184604001516104dd565b90506104b5816106ad565b60208401519092501580156104d6576104d3600160601b80856106c2565b92505b5050919050565b5f8163ffffffff165f0361055a57826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610527573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061054b91906111ea565b509495506106a7945050505050565b6040805160028082526060820183525f92602083019080368337019050509050610585836001611296565b815f8151811061059757610597610fa8565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106105c6576105c6610fa8565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81525f906001600160a01b0386169063883bdbfd906106099085906004016112ba565b5f60405180830381865afa158015610623573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261064a9190810190611373565b5090506106a28460030b825f8151811061066657610666610fa8565b60200260200101518360018151811061068157610681610fa8565b60200260200101516106939190611437565b61069d9190611478565b610833565b925050505b92915050565b5f6106a76001600160a01b03831680600160601b5b5f80805f19858709858702925082811083820303915050805f036106f6575f84116106eb575f80fd5b50829004905061082c565b808411610701575f80fd5b5f848688098084039381119092039190505f85610720811960016114b4565b16958690049593849004935f81900304600101905061073f81846114c7565b909317925f61074f8760036114c7565b600218905061075e81886114c7565b6107699060026114de565b61077390826114c7565b905061077f81886114c7565b61078a9060026114de565b61079490826114c7565b90506107a081886114c7565b6107ab9060026114de565b6107b590826114c7565b90506107c181886114c7565b6107cc9060026114de565b6107d690826114c7565b90506107e281886114c7565b6107ed9060026114de565b6107f790826114c7565b905061080381886114c7565b61080e9060026114de565b61081890826114c7565b905061082481866114c7565b955050505050505b9392505050565b5f805f8360020b12610848578260020b610855565b8260020b610855906114f1565b9050610864620d89e71961150b565b62ffffff1681111561089c5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610257565b5f816001165f036108b157600160801b6108c3565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156109025760806108fd826ffff97272373d413259a46990580e213a6114c7565b901c90505b600482161561092c576080610927826ffff2e50f5f656932ef12357cf3c7fdcc6114c7565b901c90505b6008821615610956576080610951826fffe5caca7e10e4e61c3624eaa0941cd06114c7565b901c90505b601082161561098057608061097b826fffcb9843d60f6159c9db58835c9266446114c7565b901c90505b60208216156109aa5760806109a5826fff973b41fa98c081472e6896dfb254c06114c7565b901c90505b60408216156109d45760806109cf826fff2ea16466c96a3843ec78b326b528616114c7565b901c90505b60808216156109fe5760806109f9826ffe5dee046a99a2a811c461f1969c30536114c7565b901c90505b610100821615610a29576080610a24826ffcbe86c7900a88aedcffc83b479aa3a46114c7565b901c90505b610200821615610a54576080610a4f826ff987a7253ac413176f2b074cf7815e546114c7565b901c90505b610400821615610a7f576080610a7a826ff3392b0822b70005940c7a398e4b70f36114c7565b901c90505b610800821615610aaa576080610aa5826fe7159475a2c29b7443b29c7fa6e889d96114c7565b901c90505b611000821615610ad5576080610ad0826fd097f3bdfd2022b8845ad8f792aa58256114c7565b901c90505b612000821615610b00576080610afb826fa9f746462d870fdf8a65dc1f90e061e56114c7565b901c90505b614000821615610b2b576080610b26826f70d869a156d2a1b890bb3df62baf32f76114c7565b901c90505b618000821615610b56576080610b51826f31be135f97d08fd981231505542fcfa66114c7565b901c90505b62010000821615610b82576080610b7d826f09aa508b5b7a84e1c677de54f3e99bc96114c7565b901c90505b62020000821615610bad576080610ba8826e5d6af8dedb81196699c329225ee6046114c7565b901c90505b62040000821615610bd7576080610bd2826d2216e584f5fa1ea926041bedfe986114c7565b901c90505b62080000821615610bff576080610bfa826b048a170391f7dc42444e8fa26114c7565b901c90505b5f8460020b1315610c1857610c15815f1961152b565b90505b610c276401000000008261153e565b15610c33576001610c35565b5f5b6104d39060ff16602083901c6114b4565b5f60208284031215610c56575f80fd5b5035919050565b5f81518084525f5b81811015610c8157602081850181015186830182015201610c65565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61082c6020830184610c5d565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715610ce957610ce9610cb2565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d1857610d18610cb2565b604052919050565b5f67ffffffffffffffff821115610d3957610d39610cb2565b5060051b60200190565b6001600160a01b0381168114610d57575f80fd5b50565b8015158114610d57575f80fd5b63ffffffff81168114610d57575f80fd5b5f6020808385031215610d89575f80fd5b823567ffffffffffffffff811115610d9f575f80fd5b8301601f81018513610daf575f80fd5b8035610dc2610dbd82610d20565b610cef565b81815260a09182028301840191848201919088841115610de0575f80fd5b938501935b83851015610e575780858a031215610dfb575f80fd5b610e03610cc6565b8535610e0e81610d43565b815285870135610e1d81610d5a565b81880152604086810135610e3081610d67565b90820152606086810135908201526080808701359082015283529384019391850191610de5565b50979650505050505050565b5f6020808385031215610e74575f80fd5b823567ffffffffffffffff80821115610e8b575f80fd5b818501915085601f830112610e9e575f80fd5b813581811115610eb057610eb0610cb2565b610ec2601f8201601f19168501610cef565b91508082528684828501011115610ed7575f80fd5b80848401858401375f90820190930192909252509392505050565b602080825282518282018190525f919060409081850190868401855b82811015610f6357815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610f0e565b5091979650505050505050565b600181811c90821680610f8457607f821691505b602082108103610fa257634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610fcc575f80fd5b5051919050565b601f82111561101a57805f5260205f20601f840160051c81016020851015610ff85750805b601f840160051c820191505b81811015611017575f8155600101611004565b50505b505050565b815167ffffffffffffffff81111561103957611039610cb2565b61104d816110478454610f70565b84610fd3565b602080601f831160018114611080575f84156110695750858301515b5f19600386901b1c1916600185901b1785556110d7565b5f85815260208120601f198616915b828110156110ae5788860151825594840194600190910190840161108f565b50858210156110cb57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b828152604060208201525f6110f76040830184610c5d565b949350505050565b5f6020808385031215611110575f80fd5b825167ffffffffffffffff811115611126575f80fd5b8301601f81018513611136575f80fd5b8051611144610dbd82610d20565b81815260a09182028301840191848201919088841115611162575f80fd5b938501935b83851015610e575780858a03121561117d575f80fd5b611185610cc6565b855161119081610d43565b81528587015161119f81610d5a565b818801526040868101516111b281610d67565b90820152606086810151908201526080808701519082015283529384019391850191611167565b805161ffff81168114610492575f80fd5b5f805f805f805f60e0888a031215611200575f80fd5b875161120b81610d43565b8097505060208801518060020b8114611222575f80fd5b9550611230604089016111d9565b945061123e606089016111d9565b935061124c608089016111d9565b925060a088015160ff81168114611261575f80fd5b60c089015190925061127281610d5a565b8091505092959891949750929550565b634e487b7160e01b5f52601160045260245ffd5b63ffffffff8181168382160190808211156112b3576112b3611282565b5092915050565b602080825282518282018190525f9190848201906040850190845b818110156112f757835163ffffffff16835292840192918401916001016112d5565b50909695505050505050565b5f82601f830112611312575f80fd5b81516020611322610dbd83610d20565b8083825260208201915060208460051b870101935086841115611343575f80fd5b602086015b8481101561136857805161135b81610d43565b8352918301918301611348565b509695505050505050565b5f8060408385031215611384575f80fd5b825167ffffffffffffffff8082111561139b575f80fd5b818501915085601f8301126113ae575f80fd5b815160206113be610dbd83610d20565b82815260059290921b840181019181810190898411156113dc575f80fd5b948201945b838610156114085785518060060b81146113f9575f80fd5b825294820194908201906113e1565b91880151919650909350505080821115611420575f80fd5b5061142d85828601611303565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156106a7576106a7611282565b634e487b7160e01b5f52601260045260245ffd5b5f8160060b8360060b8061148e5761148e611464565b667fffffffffffff1982145f19821416156114ab576114ab611282565b90059392505050565b808201808211156106a7576106a7611282565b80820281158282048414176106a7576106a7611282565b818103818111156106a7576106a7611282565b5f600160ff1b820161150557611505611282565b505f0390565b5f8160020b627fffff19810361152357611523611282565b5f0392915050565b5f8261153957611539611464565b500490565b5f8261154c5761154c611464565b50069056fea26469706673582212204579e3d4c88f16d070acd2de879f85800ce2ed9254a6001866db38ff34eec26464736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0x353F415320f6B5351e5516951F6eCb636CFcB4B9" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 2033, + "contract": "contracts/price_adapters/PriceAdapterUniswapV3.sol:PriceAdapterUniswapV3", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/solcInputs/b260a2753d21b48077cb0d9db054a12f.json b/packages/contracts/deployments/base/solcInputs/b260a2753d21b48077cb0d9db054a12f.json new file mode 100644 index 000000000..4b9286b1b --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/b260a2753d21b48077cb0d9db054a12f.json @@ -0,0 +1,77 @@ +{ + "language": "Solidity", + "sources": { + "contracts/interfaces/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\n}\n" + }, + "contracts/interfaces/uniswap/IUniswapV2Pair.sol": { + "content": "pragma solidity >=0.8.0;\n\ninterface IUniswapV2Pair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n function factory() external view returns (address);\n function token0() external view returns (address);\n function token1() external view returns (address);\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n function price0CumulativeLast() external view returns (uint);\n function price1CumulativeLast() external view returns (uint);\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n function burn(address to) external returns (uint amount0, uint amount1);\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n function skim(address to) external;\n function sync() external;\n\n function initialize(address, address) 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/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\n\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/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/price_adapters/PriceAdapterUniswapV2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV2Pair.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n/*\n\n UniswapV2 Price Adapter (compatible with Sushiswap and other V2 forks)\n Uses reserves for current price \n\n\n Cannot compute TWAP price as uniswapV2 doesnt provide historic data \n\n*/\n\n\ncontract PriceAdapterUniswapV2 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // Get sqrtPriceX96 from UniswapV2 reserves\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address uniswapV2Pool, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pool);\n\n if (twapInterval == 0) {\n // Use current reserves for immediate price\n (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();\n sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1));\n } else {\n // For TWAP, use cumulative prices\n // Note: In a single transaction, we can only get the current cumulative prices\n // This requires storing historical cumulative prices on-chain for proper TWAP calculation\n // For now, we use current reserves as a fallback\n (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();\n sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1));\n }\n }\n\n function getSqrtPriceX96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n // Calculate sqrt(reserve1 / reserve0) * 2^96\n // This represents the price of token0 in terms of token1\n\n require(reserve0 > 0, \"Reserve0 cannot be zero\");\n require(reserve1 > 0, \"Reserve1 cannot be zero\");\n\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n }\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n\n require( route_array.length ==1 || route_array.length ==2, \"invalid route length\" );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\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 383d356f5d5557148ab6ac183b1cd93837c79ae6 Mon Sep 17 00:00:00 2001 From: andy Date: Fri, 13 Feb 2026 21:21:32 -0500 Subject: [PATCH 38/46] updated repo to node 20 , deployed contract on BSC --- .nvmrc | 1 + package.json | 4 +- packages/contracts/.openzeppelin/bsc.json | 3187 +++++++++++++++++ packages/contracts/.prettierrc.yml | 3 + .../contracts/NEW_NETWORK_DEPLOYMENT_PLAN.md | 297 ++ .../deploy/admin/timelock_controller.ts | 2 +- .../deploy_alpha.ts | 2 +- .../lender_commitment_group_v2_beacon.ts | 2 +- .../lender_groups_factory_v2.ts | 2 +- .../uniswap_pricing_libraryV2.ts | 2 +- .../deploy/oracle/mock_hypernative_oracle.ts | 2 +- .../deploy/pricing/uniswap_pricing_helper.ts | 2 +- .../smart_commitment_forwarder/deploy.ts | 2 +- .../contracts/deploy/teller_v2/initialize.ts | 13 +- .../teller_v2/protocol_pausing_manager.ts | 2 +- packages/contracts/deployments/bsc/.chainId | 1 + .../deployments/bsc/.latestDeploymentBlock | 1 + .../deployments/bsc/.migrations.json | 24 + .../bsc/CollateralEscrowBeacon.json | 350 ++ .../deployments/bsc/CollateralManager.json | 721 ++++ .../deployments/bsc/EscrowVault.json | 101 + .../deployments/bsc/HypernativeOracle.json | 737 ++++ .../bsc/LenderCommitmentForwarderAlpha.json | 1189 ++++++ .../bsc/LenderCommitmentGroupBeaconV2.json | 2017 +++++++++++ .../bsc/LenderCommitmentGroupFactory_V2.json | 218 ++ .../deployments/bsc/LenderManager.json | 441 +++ .../bsc/MarketLiquidityRewards.json | 405 +++ .../deployments/bsc/MarketRegistry.json | 1390 +++++++ .../deployments/bsc/MetaForwarder.json | 155 + .../bsc/ProtocolPausingManager.json | 310 ++ .../deployments/bsc/ReputationManager.json | 218 ++ .../bsc/SmartCommitmentForwarder.json | 578 +++ .../deployments/bsc/SwapRolloverLoan.json | 514 +++ .../contracts/deployments/bsc/TellerAS.json | 1089 ++++++ .../bsc/TellerASEIP712Verifier.json | 273 ++ .../deployments/bsc/TellerASRegistry.json | 285 ++ .../contracts/deployments/bsc/TellerV2.json | 1761 +++++++++ .../deployments/bsc/TimelockController.json | 1246 +++++++ .../deployments/bsc/UniswapPricingHelper.json | 133 + .../bsc/UniswapPricingLibrary.json | 133 + .../bsc/UniswapPricingLibraryV2.json | 133 + .../deployments/bsc/V2Calculations.json | 149 + .../0734360f150a1a42bdf38edcad8bf3ab.json | 890 +++++ packages/contracts/hardhat.config.ts | 33 +- .../helpers/ecosystem-contracts-lookup.ts | 6 + packages/contracts/package.json | 27 +- packages/subgraph-pool-v2/package.json | 12 +- packages/subgraph-pool/package.json | 12 +- packages/subgraph/package.json | 12 +- 49 files changed, 19033 insertions(+), 54 deletions(-) create mode 100644 .nvmrc create mode 100644 packages/contracts/.openzeppelin/bsc.json create mode 100644 packages/contracts/NEW_NETWORK_DEPLOYMENT_PLAN.md create mode 100644 packages/contracts/deployments/bsc/.chainId create mode 100644 packages/contracts/deployments/bsc/.latestDeploymentBlock create mode 100644 packages/contracts/deployments/bsc/.migrations.json create mode 100644 packages/contracts/deployments/bsc/CollateralEscrowBeacon.json create mode 100644 packages/contracts/deployments/bsc/CollateralManager.json create mode 100644 packages/contracts/deployments/bsc/EscrowVault.json create mode 100644 packages/contracts/deployments/bsc/HypernativeOracle.json create mode 100644 packages/contracts/deployments/bsc/LenderCommitmentForwarderAlpha.json create mode 100644 packages/contracts/deployments/bsc/LenderCommitmentGroupBeaconV2.json create mode 100644 packages/contracts/deployments/bsc/LenderCommitmentGroupFactory_V2.json create mode 100644 packages/contracts/deployments/bsc/LenderManager.json create mode 100644 packages/contracts/deployments/bsc/MarketLiquidityRewards.json create mode 100644 packages/contracts/deployments/bsc/MarketRegistry.json create mode 100644 packages/contracts/deployments/bsc/MetaForwarder.json create mode 100644 packages/contracts/deployments/bsc/ProtocolPausingManager.json create mode 100644 packages/contracts/deployments/bsc/ReputationManager.json create mode 100644 packages/contracts/deployments/bsc/SmartCommitmentForwarder.json create mode 100644 packages/contracts/deployments/bsc/SwapRolloverLoan.json create mode 100644 packages/contracts/deployments/bsc/TellerAS.json create mode 100644 packages/contracts/deployments/bsc/TellerASEIP712Verifier.json create mode 100644 packages/contracts/deployments/bsc/TellerASRegistry.json create mode 100644 packages/contracts/deployments/bsc/TellerV2.json create mode 100644 packages/contracts/deployments/bsc/TimelockController.json create mode 100644 packages/contracts/deployments/bsc/UniswapPricingHelper.json create mode 100644 packages/contracts/deployments/bsc/UniswapPricingLibrary.json create mode 100644 packages/contracts/deployments/bsc/UniswapPricingLibraryV2.json create mode 100644 packages/contracts/deployments/bsc/V2Calculations.json create mode 100644 packages/contracts/deployments/bsc/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 000000000..209e3ef4b --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +20 diff --git a/package.json b/package.json index a1cee46fc..e6388a5a0 100644 --- a/package.json +++ b/package.json @@ -27,10 +27,10 @@ }, "packageManager": "yarn@3.6.1", "devDependencies": { - "eslint": "^7.32.0", + "eslint": "^8.56.0", "husky": "^8.0.1", "mustache": "^4.2.0", - "prettier": "^2.4.1", + "prettier": "^3.2.0", "shx": "^0.3.3" } } diff --git a/packages/contracts/.openzeppelin/bsc.json b/packages/contracts/.openzeppelin/bsc.json new file mode 100644 index 000000000..6cabc0a32 --- /dev/null +++ b/packages/contracts/.openzeppelin/bsc.json @@ -0,0 +1,3187 @@ +{ + "manifestVersion": "3.2", + "admin": { + "address": "0x5d3eCF8877eDAB28e14bD7d243fA8B0fE416E95E", + "txHash": "0x1ddcb18456a99f364975c6a9d53867f15782efd81e10bf15c9845fbe6560a6c8" + }, + "proxies": [ + { + "address": "0xE11884953B18F8ddC55875CBDAb71b624779D3bB", + "txHash": "0xa9e9223f9263ca47dfc7594bb8d0441a09d73407cdc995a3537acead67764072", + "kind": "transparent" + }, + { + "address": "0x90D08f8Df66dFdE93801783FF7A36876453DAE75", + "txHash": "0x1fc7bcdf09102a0b3143d8a87ec810fc68f3a7e531781b523d66f6bfcdb865bc", + "kind": "transparent" + }, + { + "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", + "txHash": "0x08593d76000eb958309a753e65bb7ea708b578dfd6082fb6d66cb9b5351b049d", + "kind": "transparent" + }, + { + "address": "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04", + "txHash": "0xffd1a811874b826260c992e5e38ff1f29aba29aaf75fbcd5e558dbe766034667", + "kind": "transparent" + }, + { + "address": "0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515", + "txHash": "0x82a311fab5d5f8ef1c32803b5e6f8ee36fcf3a67c09eda7b78b93963060c2fc4", + "kind": "transparent" + }, + { + "address": "0xfCd6Aa92D399260E8309800316CEc9b1F123621e", + "txHash": "0x52cca139a342510c50ba8fc203f46dd066b1b266fa9692e9d1231e81516b8bb4", + "kind": "transparent" + }, + { + "address": "0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB", + "txHash": "0x938c06f23014d88b7ff83441566a4993c653d567371fcb8ce6b35451b2c42bf4", + "kind": "transparent" + }, + { + "address": "0xfDDcEc68cfa40c38Faf05F918484fC416a221BFF", + "txHash": "0x205aae99a111ce69d7fd9baa2b97a40707f465e0637b055cbb1848f70dc00336", + "kind": "transparent" + }, + { + "address": "0x7292385522F11390B2A7dd4677528fFce03b80db", + "txHash": "0x8bc368aa14a89ce357de79e93b358a1942e1a5006d291564b11390df24dfc18a", + "kind": "transparent" + }, + { + "address": "0xb7695470E9c8d6E84F4786C240960B7822106b63", + "txHash": "0x1f9c3cfd8e697e3675cb91a56ad82b12f6e7d1db4be9984fc709995e3fa5b851", + "kind": "transparent" + }, + { + "address": "0x357fa5700f67a3DA1EC49ea19F872B3a35fE043D", + "txHash": "0xe47a5df72d3bda7d7d67e6e8d37d37d78f917c1dd3abeee12553206ab5a4ae47", + "kind": "transparent" + }, + { + "address": "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa", + "txHash": "0x8d2336b8b278516440d04a0c57a3c501bd0a1816e40c5f57d83506d19ba74caa", + "kind": "transparent" + }, + { + "address": "0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D", + "txHash": "0xb9250e2f1926b689e5dc1b5431d80ff350fad77714b9b55bee47bd8fb15130df", + "kind": "transparent" + } + ], + "impls": { + "ce39878ecd9200ccdebe2ced384987a3a016d16553069380ba583f8183124209": { + "address": "0x928685Fd2ce2A3E8909a9f473a85648Ca3689860", + "txHash": "0xe256f0872d963c30cae2c62d0e927813683e44d853760d43b0f8a03677d1ee2f", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "bidId", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "CollateralEscrowV1", + "src": "contracts/escrow/CollateralEscrowV1.sol:17" + }, + { + "label": "collateralBalances", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_struct(Collateral)51767_storage)", + "contract": "CollateralEscrowV1", + "src": "contracts/escrow/CollateralEscrowV1.sol:19" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_enum(CollateralType)51757": { + "label": "enum CollateralType", + "members": [ + "ERC20", + "ERC721", + "ERC1155" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_struct(Collateral)51767_storage)": { + "label": "mapping(address => struct Collateral)", + "numberOfBytes": "32" + }, + "t_struct(Collateral)51767_storage": { + "label": "struct Collateral", + "members": [ + { + "label": "_collateralType", + "type": "t_enum(CollateralType)51757", + "offset": 0, + "slot": "0" + }, + { + "label": "_amount", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "_tokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "_collateralAddress", + "type": "t_address", + "offset": 0, + "slot": "3" + } + ], + "numberOfBytes": "128" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "032c39add4d0355222025ad6d0b242e0fa061dbd76a18f52856a1551a3cadfac": { + "address": "0xe7768f28455eE81D7B415f4F5019A316c27AB445", + "txHash": "0x98cb203fc946d5f3e1ca9983c5c6a172019f32e00b5ca9e5f3b80807f6841c23", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "_HASHED_NAME", + "offset": 0, + "slot": "1", + "type": "t_bytes32", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:32" + }, + { + "label": "_HASHED_VERSION", + "offset": 0, + "slot": "2", + "type": "t_bytes32", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:33" + }, + { + "label": "__gap", + "offset": 0, + "slot": "3", + "type": "t_array(t_uint256)50_storage", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:120" + }, + { + "label": "_nonces", + "offset": 0, + "slot": "53", + "type": "t_mapping(t_address,t_uint256)", + "contract": "MinimalForwarderUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:33" + }, + { + "label": "__gap", + "offset": 0, + "slot": "54", + "type": "t_array(t_uint256)49_storage", + "contract": "MinimalForwarderUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:84" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "06a1505bd44d1757245b66660cdc03e2ffcb7ebcf3a978a7ccb17a52c9f10d72": { + "address": "0xf7B14778035fEAF44540A0bC1D4ED859bCB28229", + "txHash": "0x12e365d9e59353170625bc63e34a7413c6fa6e4b6a78f9eafe73460e51bdbc6a", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_protocolFee", + "offset": 0, + "slot": "101", + "type": "t_uint16", + "contract": "ProtocolFee", + "src": "contracts/ProtocolFee.sol:8" + }, + { + "label": "__paused", + "offset": 2, + "slot": "101", + "type": "t_bool", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:18" + }, + { + "label": "_protocolPausingManager", + "offset": 3, + "slot": "101", + "type": "t_address", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:20" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:57" + }, + { + "label": "bidId", + "offset": 0, + "slot": "151", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:92" + }, + { + "label": "bids", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_uint256,t_struct(Bid)44648_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:95" + }, + { + "label": "borrowerBids", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_address,t_array(t_uint256)dyn_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:98" + }, + { + "label": "__lenderVolumeFilled", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_address,t_uint256)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:101" + }, + { + "label": "__totalVolumeFilled", + "offset": 0, + "slot": "155", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:104" + }, + { + "label": "__lendingTokensSet", + "offset": 0, + "slot": "156", + "type": "t_struct(AddressSet)13999_storage", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:107" + }, + { + "label": "marketRegistry", + "offset": 0, + "slot": "158", + "type": "t_contract(IMarketRegistry)49610", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:109" + }, + { + "label": "reputationManager", + "offset": 0, + "slot": "159", + "type": "t_contract(IReputationManager)49705", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:110" + }, + { + "label": "_borrowerBidsActive", + "offset": 0, + "slot": "160", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:113" + }, + { + "label": "bidDefaultDuration", + "offset": 0, + "slot": "161", + "type": "t_mapping(t_uint256,t_uint32)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:115" + }, + { + "label": "bidExpirationTime", + "offset": 0, + "slot": "162", + "type": "t_mapping(t_uint256,t_uint32)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:116" + }, + { + "label": "lenderVolumeFilled", + "offset": 0, + "slot": "163", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:120" + }, + { + "label": "totalVolumeFilled", + "offset": 0, + "slot": "164", + "type": "t_mapping(t_address,t_uint256)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:124" + }, + { + "label": "version", + "offset": 0, + "slot": "165", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:126" + }, + { + "label": "uris", + "offset": 0, + "slot": "166", + "type": "t_mapping(t_uint256,t_string_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:130" + }, + { + "label": "_trustedMarketForwarders", + "offset": 0, + "slot": "167", + "type": "t_mapping(t_uint256,t_address)", + "contract": "TellerV2Storage_G1", + "src": "contracts/TellerV2Storage.sol:135" + }, + { + "label": "_approvedForwarderSenders", + "offset": 0, + "slot": "168", + "type": "t_mapping(t_address,t_struct(AddressSet)13999_storage)", + "contract": "TellerV2Storage_G1", + "src": "contracts/TellerV2Storage.sol:137" + }, + { + "label": "lenderCommitmentForwarder", + "offset": 0, + "slot": "169", + "type": "t_address", + "contract": "TellerV2Storage_G2", + "src": "contracts/TellerV2Storage.sol:142" + }, + { + "label": "collateralManager", + "offset": 0, + "slot": "170", + "type": "t_contract(ICollateralManager)48330", + "contract": "TellerV2Storage_G3", + "src": "contracts/TellerV2Storage.sol:146" + }, + { + "label": "lenderManager", + "offset": 0, + "slot": "171", + "type": "t_contract(ILenderManager)49339", + "contract": "TellerV2Storage_G4", + "src": "contracts/TellerV2Storage.sol:151" + }, + { + "label": "bidPaymentCycleType", + "offset": 0, + "slot": "172", + "type": "t_mapping(t_uint256,t_enum(PaymentCycleType)54768)", + "contract": "TellerV2Storage_G4", + "src": "contracts/TellerV2Storage.sol:153" + }, + { + "label": "escrowVault", + "offset": 0, + "slot": "173", + "type": "t_contract(IEscrowVault)48831", + "contract": "TellerV2Storage_G5", + "src": "contracts/TellerV2Storage.sol:158" + }, + { + "label": "repaymentListenerForBid", + "offset": 0, + "slot": "174", + "type": "t_mapping(t_uint256,t_address)", + "contract": "TellerV2Storage_G6", + "src": "contracts/TellerV2Storage.sol:162" + }, + { + "label": "__pauserRoleBearer", + "offset": 0, + "slot": "175", + "type": "t_mapping(t_address,t_bool)", + "contract": "TellerV2Storage_G7", + "src": "contracts/TellerV2Storage.sol:166" + }, + { + "label": "__liquidationsPaused", + "offset": 0, + "slot": "176", + "type": "t_bool", + "contract": "TellerV2Storage_G7", + "src": "contracts/TellerV2Storage.sol:167" + }, + { + "label": "protocolFeeRecipient", + "offset": 1, + "slot": "176", + "type": "t_address", + "contract": "TellerV2Storage_G8", + "src": "contracts/TellerV2Storage.sol:171" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "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_array(t_uint256)dyn_storage": { + "label": "uint256[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(ICollateralManager)48330": { + "label": "contract ICollateralManager", + "numberOfBytes": "20" + }, + "t_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_contract(IEscrowVault)48831": { + "label": "contract IEscrowVault", + "numberOfBytes": "20" + }, + "t_contract(ILenderManager)49339": { + "label": "contract ILenderManager", + "numberOfBytes": "20" + }, + "t_contract(IMarketRegistry)49610": { + "label": "contract IMarketRegistry", + "numberOfBytes": "20" + }, + "t_contract(IReputationManager)49705": { + "label": "contract IReputationManager", + "numberOfBytes": "20" + }, + "t_enum(BidState)44620": { + "label": "enum BidState", + "members": [ + "NONEXISTENT", + "PENDING", + "CANCELLED", + "ACCEPTED", + "PAID", + "LIQUIDATED", + "CLOSED" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentCycleType)54768": { + "label": "enum PaymentCycleType", + "members": [ + "Seconds", + "Monthly" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentType)54765": { + "label": "enum PaymentType", + "members": [ + "EMI", + "Bullet" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_array(t_uint256)dyn_storage)": { + "label": "mapping(address => uint256[])", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_struct(AddressSet)13999_storage)": { + "label": "mapping(address => struct EnumerableSet.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_struct(UintSet)14156_storage)": { + "label": "mapping(address => struct EnumerableSet.UintSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_enum(PaymentCycleType)54768)": { + "label": "mapping(uint256 => enum PaymentCycleType)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_string_storage)": { + "label": "mapping(uint256 => string)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Bid)44648_storage)": { + "label": "mapping(uint256 => struct Bid)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint32)": { + "label": "mapping(uint256 => uint32)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)13999_storage": { + "label": "struct EnumerableSet.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Bid)44648_storage": { + "label": "struct Bid", + "members": [ + { + "label": "borrower", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "receiver", + "type": "t_address", + "offset": 0, + "slot": "1" + }, + { + "label": "lender", + "type": "t_address", + "offset": 0, + "slot": "2" + }, + { + "label": "marketplaceId", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "_metadataURI", + "type": "t_bytes32", + "offset": 0, + "slot": "4" + }, + { + "label": "loanDetails", + "type": "t_struct(LoanDetails)44665_storage", + "offset": 0, + "slot": "5" + }, + { + "label": "terms", + "type": "t_struct(Terms)44672_storage", + "offset": 0, + "slot": "10" + }, + { + "label": "state", + "type": "t_enum(BidState)44620", + "offset": 0, + "slot": "12" + }, + { + "label": "paymentType", + "type": "t_enum(PaymentType)54765", + "offset": 1, + "slot": "12" + } + ], + "numberOfBytes": "416" + }, + "t_struct(LoanDetails)44665_storage": { + "label": "struct LoanDetails", + "members": [ + { + "label": "lendingToken", + "type": "t_contract(IERC20)8314", + "offset": 0, + "slot": "0" + }, + { + "label": "principal", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "totalRepaid", + "type": "t_struct(Payment)44625_storage", + "offset": 0, + "slot": "2" + }, + { + "label": "timestamp", + "type": "t_uint32", + "offset": 0, + "slot": "4" + }, + { + "label": "acceptedTimestamp", + "type": "t_uint32", + "offset": 4, + "slot": "4" + }, + { + "label": "lastRepaidTimestamp", + "type": "t_uint32", + "offset": 8, + "slot": "4" + }, + { + "label": "loanDuration", + "type": "t_uint32", + "offset": 12, + "slot": "4" + } + ], + "numberOfBytes": "160" + }, + "t_struct(Payment)44625_storage": { + "label": "struct Payment", + "members": [ + { + "label": "principal", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "interest", + "type": "t_uint256", + "offset": 0, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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_struct(Terms)44672_storage": { + "label": "struct Terms", + "members": [ + { + "label": "paymentCycleAmount", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "paymentCycle", + "type": "t_uint32", + "offset": 0, + "slot": "1" + }, + { + "label": "APR", + "type": "t_uint16", + "offset": 4, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_struct(UintSet)14156_storage": { + "label": "struct EnumerableSet.UintSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "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": {} + } + }, + "0d4a31f6f624b9c75868f8aea57e4c032618e937096f23cbd615456f3839a1e1": { + "address": "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f", + "txHash": "0x0f8f8acbbe8883abe5f2655174434ffbef97ddcafb7afb1f0008566483017ac3", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "tellerV2", + "offset": 0, + "slot": "101", + "type": "t_contract(ITellerV2)50063", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:24" + }, + { + "label": "collateralEscrowBeacon", + "offset": 0, + "slot": "102", + "type": "t_address", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:25" + }, + { + "label": "_escrows", + "offset": 0, + "slot": "103", + "type": "t_mapping(t_uint256,t_address)", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:28" + }, + { + "label": "_bidCollaterals", + "offset": 0, + "slot": "104", + "type": "t_mapping(t_uint256,t_struct(CollateralInfo)14335_storage)", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:30" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "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_contract(ITellerV2)50063": { + "label": "contract ITellerV2", + "numberOfBytes": "20" + }, + "t_enum(CollateralType)51757": { + "label": "enum CollateralType", + "members": [ + "ERC20", + "ERC721", + "ERC1155" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_struct(Collateral)51767_storage)": { + "label": "mapping(address => struct Collateral)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(CollateralInfo)14335_storage)": { + "label": "mapping(uint256 => struct CollateralManager.CollateralInfo)", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)5821_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)5506_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Collateral)51767_storage": { + "label": "struct Collateral", + "members": [ + { + "label": "_collateralType", + "type": "t_enum(CollateralType)51757", + "offset": 0, + "slot": "0" + }, + { + "label": "_amount", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "_tokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "_collateralAddress", + "type": "t_address", + "offset": 0, + "slot": "3" + } + ], + "numberOfBytes": "128" + }, + "t_struct(CollateralInfo)14335_storage": { + "label": "struct CollateralManager.CollateralInfo", + "members": [ + { + "label": "collateralAddresses", + "type": "t_struct(AddressSet)5821_storage", + "offset": 0, + "slot": "0" + }, + { + "label": "collateralInfo", + "type": "t_mapping(t_address,t_struct(Collateral)51767_storage)", + "offset": 0, + "slot": "2" + } + ], + "numberOfBytes": "96" + }, + "t_struct(Set)5506_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_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "3da6928b9090457692f910cf04bdd97c5a502e94c34c623e931d0082a9e15f58": { + "address": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", + "txHash": "0xf1fe3e11e67344ce911319751a806d84ed3404c9579d000fdddd8d06e4349c99", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "balances", + "offset": 0, + "slot": "51", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "EscrowVault", + "src": "contracts/EscrowVault.sol:21" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)50_storage": { + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "80889dce3a01abff40361826aa8e12a56254a298b2db1bc457492a6524584da3": { + "address": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b", + "txHash": "0x059401a79738686963e026ca4532dfc2172df747f3146a80fdd2f2c37dda5259", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" + }, + { + "label": "lenderAttestationSchemaId", + "offset": 0, + "slot": "1", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:52" + }, + { + "label": "markets", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_uint256,t_struct(Marketplace)38479_storage)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:54" + }, + { + "label": "__uriToId", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_bytes32,t_uint256)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:55" + }, + { + "label": "marketCount", + "offset": 0, + "slot": "4", + "type": "t_uint256", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:56" + }, + { + "label": "_attestingSchemaId", + "offset": 0, + "slot": "5", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:57" + }, + { + "label": "borrowerAttestationSchemaId", + "offset": 0, + "slot": "6", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:58" + }, + { + "label": "version", + "offset": 0, + "slot": "7", + "type": "t_uint256", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:60" + }, + { + "label": "marketIsClosed", + "offset": 0, + "slot": "8", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:62" + }, + { + "label": "tellerAS", + "offset": 0, + "slot": "9", + "type": "t_contract(TellerAS)16551", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:64" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(TellerAS)16551": { + "label": "contract TellerAS", + "numberOfBytes": "20" + }, + "t_enum(PaymentCycleType)54768": { + "label": "enum PaymentCycleType", + "members": [ + "Seconds", + "Monthly" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentType)54765": { + "label": "enum PaymentType", + "members": [ + "EMI", + "Bullet" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_bytes32)": { + "label": "mapping(address => bytes32)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Marketplace)38479_storage)": { + "label": "mapping(uint256 => struct MarketRegistry.Marketplace)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)13999_storage": { + "label": "struct EnumerableSet.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Marketplace)38479_storage": { + "label": "struct MarketRegistry.Marketplace", + "members": [ + { + "label": "owner", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "metadataURI", + "type": "t_string_storage", + "offset": 0, + "slot": "1" + }, + { + "label": "marketplaceFeePercent", + "type": "t_uint16", + "offset": 0, + "slot": "2" + }, + { + "label": "lenderAttestationRequired", + "type": "t_bool", + "offset": 2, + "slot": "2" + }, + { + "label": "verifiedLendersForMarket", + "type": "t_struct(AddressSet)13999_storage", + "offset": 0, + "slot": "3" + }, + { + "label": "lenderAttestationIds", + "type": "t_mapping(t_address,t_bytes32)", + "offset": 0, + "slot": "5" + }, + { + "label": "paymentCycleDuration", + "type": "t_uint32", + "offset": 0, + "slot": "6" + }, + { + "label": "paymentDefaultDuration", + "type": "t_uint32", + "offset": 4, + "slot": "6" + }, + { + "label": "bidExpirationTime", + "type": "t_uint32", + "offset": 8, + "slot": "6" + }, + { + "label": "borrowerAttestationRequired", + "type": "t_bool", + "offset": 12, + "slot": "6" + }, + { + "label": "verifiedBorrowersForMarket", + "type": "t_struct(AddressSet)13999_storage", + "offset": 0, + "slot": "7" + }, + { + "label": "borrowerAttestationIds", + "type": "t_mapping(t_address,t_bytes32)", + "offset": 0, + "slot": "9" + }, + { + "label": "feeRecipient", + "type": "t_address", + "offset": 0, + "slot": "10" + }, + { + "label": "paymentType", + "type": "t_enum(PaymentType)54765", + "offset": 20, + "slot": "10" + }, + { + "label": "paymentCycleType", + "type": "t_enum(PaymentCycleType)54768", + "offset": 21, + "slot": "10" + } + ], + "numberOfBytes": "352" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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": {} + } + }, + "59da181c273f4bd03bec57e2a33af721cf9fc478e2768226374c7b64bc04676a": { + "address": "0xa1106d888F1FA689c6935e0983687432eF2a28c1", + "txHash": "0x572f2d4603729cdb7ae6e63c6556d2fd1d5ba213fd0113d485d8787740e762ab", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" + }, + { + "label": "tellerV2", + "offset": 2, + "slot": "0", + "type": "t_contract(ITellerV2)50063", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:17" + }, + { + "label": "_delinquencies", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:18" + }, + { + "label": "_defaults", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:19" + }, + { + "label": "_currentDelinquencies", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:20" + }, + { + "label": "_currentDefaults", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:21" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(ITellerV2)50063": { + "label": "contract ITellerV2", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_struct(UintSet)14156_storage)": { + "label": "mapping(address => struct EnumerableSet.UintSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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_struct(UintSet)14156_storage": { + "label": "struct EnumerableSet.UintSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "3935351dabf53c1fc4eb5ca7f665a4e9fa44be0c859fa388c43268b0703401b2": { + "address": "0x7FBCefE4aE4c0C9E70427D0B9F1504Ed39d141BC", + "txHash": "0x6c6334bd19168613e0997d80a5f582cfc2e57f61b85212f8f3c22d010221761c", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "__gap", + "offset": 0, + "slot": "101", + "type": "t_array(t_uint256)50_storage", + "contract": "ERC165Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "151", + "type": "t_string_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:25" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "152", + "type": "t_string_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:28" + }, + { + "label": "_owners", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_address)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:31" + }, + { + "label": "_balances", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:34" + }, + { + "label": "_tokenApprovals", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_address)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:37" + }, + { + "label": "_operatorApprovals", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:40" + }, + { + "label": "__gap", + "offset": 0, + "slot": "157", + "type": "t_array(t_uint256)44_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:514" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)44_storage": { + "label": "uint256[44]", + "numberOfBytes": "1408" + }, + "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_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_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "81a14ec7faa3026d35f6b1f491b0f6175469a86e368337cd3b65e5179ff53faa": { + "address": "0x7f43c21D4FE1807BF2CF25e6F048A03b57226e03", + "txHash": "0x01274eb8808d8e9c75710f03b5309793264e2069067dff2f818b1b5291ffcbed", + "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)49060_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:53" + }, + { + "label": "commitmentCount", + "offset": 0, + "slot": "152", + "type": "t_uint256", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:55" + }, + { + "label": "commitmentBorrowersList", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_struct(AddressSet)5821_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:58" + }, + { + "label": "commitmentPrincipalAccepted", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:62" + }, + { + "label": "commitmentUniswapPoolRoutes", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)49071_storage)dyn_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:64" + }, + { + "label": "commitmentPoolOracleLtvRatio", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_uint256,t_uint16)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:66" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(PoolRouteConfig)49071_storage)dyn_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)49036": { + "label": "enum ILenderCommitmentForwarder_U1.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)49071_storage)dyn_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(AddressSet)5821_storage)": { + "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Commitment)49060_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)5821_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)5506_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Commitment)49060_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)49036", + "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)49071_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)5506_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": {} + } + }, + "feefcdf14aaffae071c6892c4ce6731884d70a632572a85efc349e172136f2c6": { + "address": "0x203ee2F172826Fa46A175230DF260188fE0C96Fc", + "txHash": "0x6c8b305c9ff79ab0076465b1ac39866c4ac3452eeb3389cadc107d93f8d8e316", + "layout": { + "solcVersion": "0.8.11", + "storage": [], + "types": {}, + "namespaces": {} + } + }, + "5eb682193970e6e8a9871711032bcc2edcd81a99990c5f1facfeff239c500f2d": { + "address": "0x48EE9c344d5C6d202F4b3225A694957a3412008d", + "txHash": "0x144a65090beef0152447c8a5086c2438a38ac58564476b7cd3419be83d0c7bf5", + "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": "__gap", + "offset": 0, + "slot": "151", + "type": "t_array(t_uint256)50_storage", + "contract": "TellerV2MarketForwarder_G3", + "src": "contracts/TellerV2MarketForwarder_G3.sol:59" + }, + { + "label": "_paused", + "offset": 0, + "slot": "201", + "type": "t_bool", + "contract": "PausableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)49_storage", + "contract": "PausableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" + }, + { + "label": "_status", + "offset": 0, + "slot": "251", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "252", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_owner", + "offset": 0, + "slot": "301", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "302", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "liquidationProtocolFeePercent", + "offset": 0, + "slot": "351", + "type": "t_uint256", + "contract": "SmartCommitmentForwarder", + "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:88" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "352", + "type": "t_uint256", + "contract": "SmartCommitmentForwarder", + "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:89" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_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_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "c8d7b90093e71c94d09f4e272108089f270011c5e03a0bf523ee49820a9ed773": { + "address": "0x13a5735F356B4ede9D3F65D3eDdb62651df1cC37", + "txHash": "0xed1f6570aac6746335244a543d57867b18793b6d041792d9304075e424bfad83", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_protocolPaused", + "offset": 0, + "slot": "101", + "type": "t_bool", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:23" + }, + { + "label": "_liquidationsPaused", + "offset": 1, + "slot": "101", + "type": "t_bool", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:24" + }, + { + "label": "pauserRoleBearer", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_bool)", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:26" + }, + { + "label": "lastPausedAt", + "offset": 0, + "slot": "103", + "type": "t_uint256", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:29" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "104", + "type": "t_uint256", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:30" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "098258ace37d2910325cdcb9893ff5bd8f9439415164d4b86f3473e1f0e27521": { + "address": "0xf6E926D7282Ba2Dc1bd580dA36420d2067bEc4A3", + "txHash": "0x9c1c9e2bcdd2470d86a58b4ad92885017f5ba4d5ce80232bcaad85d606d386c6", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_status", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" + }, + { + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" + }, + { + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" + }, + { + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" + }, + { + "label": "poolSharesLastTransferredAt", + "offset": 0, + "slot": "201", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)50_storage", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" + }, + { + "label": "principalToken", + "offset": 0, + "slot": "252", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:119" + }, + { + "label": "collateralToken", + "offset": 0, + "slot": "253", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:120" + }, + { + "label": "marketId", + "offset": 0, + "slot": "254", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:122" + }, + { + "label": "totalPrincipalTokensCommitted", + "offset": 0, + "slot": "255", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:125" + }, + { + "label": "totalPrincipalTokensWithdrawn", + "offset": 0, + "slot": "256", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:126" + }, + { + "label": "totalPrincipalTokensLended", + "offset": 0, + "slot": "257", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:128" + }, + { + "label": "totalPrincipalTokensRepaid", + "offset": 0, + "slot": "258", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:129" + }, + { + "label": "excessivePrincipalTokensRepaid", + "offset": 0, + "slot": "259", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:130" + }, + { + "label": "totalInterestCollected", + "offset": 0, + "slot": "260", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:132" + }, + { + "label": "liquidityThresholdPercent", + "offset": 0, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:134" + }, + { + "label": "collateralRatio", + "offset": 2, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:135" + }, + { + "label": "maxLoanDuration", + "offset": 4, + "slot": "261", + "type": "t_uint32", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:137" + }, + { + "label": "interestRateLowerBound", + "offset": 8, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:138" + }, + { + "label": "interestRateUpperBound", + "offset": 10, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:139" + }, + { + "label": "activeBids", + "offset": 0, + "slot": "262", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:147" + }, + { + "label": "activeBidsAmountDueRemaining", + "offset": 0, + "slot": "263", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:148" + }, + { + "label": "tokenDifferenceFromLiquidations", + "offset": 0, + "slot": "264", + "type": "t_int256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:150" + }, + { + "label": "firstDepositMade_deprecated", + "offset": 0, + "slot": "265", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:152" + }, + { + "label": "withdrawDelayTimeSeconds", + "offset": 0, + "slot": "266", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:153" + }, + { + "label": "poolOracleRoutes", + "offset": 0, + "slot": "267", + "type": "t_array(t_struct(PoolRouteConfig)50152_storage)dyn_storage", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:155" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "offset": 0, + "slot": "268", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:158" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "269", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:161" + }, + { + "label": "paused", + "offset": 0, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:162" + }, + { + "label": "borrowingPaused", + "offset": 1, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:163" + }, + { + "label": "liquidationAuctionPaused", + "offset": 2, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:164" + }, + { + "label": "withdrawDelayBypassForAccount", + "offset": 0, + "slot": "271", + "type": "t_mapping(t_address,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:166" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_struct(PoolRouteConfig)50152_storage)dyn_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", + "numberOfBytes": "32" + }, + "t_array(t_uint256)45_storage": { + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "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_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_int256": { + "label": "int256", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(PoolRouteConfig)50152_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_uint16": { + "label": "uint16", + "numberOfBytes": "2" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint32": { + "label": "uint32", + "numberOfBytes": "4" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "6f01541265576f4854242ff526c30b4e304ae07d7b0c03a7210326a561fea83e": { + "address": "0x437b82f48Cd7E60742C87f4DF45eCf13B6CA935c", + "txHash": "0x291301afafe4fa90198340c8e476359233cd91b0b5d122f462f02834f30b093b", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "lenderGroupBeacon", + "offset": 0, + "slot": "101", + "type": "t_address", + "contract": "LenderCommitmentGroupFactory_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:32" + }, + { + "label": "deployedLenderGroupContracts", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupFactory_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:36" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "ef57860fbbb4db0e9871ad4483186b6c895fe4031de3c6fddb1227d842e78984": { + "address": "0x5360af9B95701504F783d8654bA02B0AF5155f64", + "txHash": "0x744e6f404c7517d88b91a73405b894bd98191bdad60f8a4cccae1f8c0941a656", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "allocationCount", + "offset": 0, + "slot": "1", + "type": "t_uint256", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:31" + }, + { + "label": "allocatedRewards", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_uint256,t_struct(RewardAllocation)49396_storage)", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:34" + }, + { + "label": "rewardClaimedForBid", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:37" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_enum(AllocationStrategy)49399": { + "label": "enum IMarketLiquidityRewards.AllocationStrategy", + "members": [ + "BORROWER", + "LENDER" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))": { + "label": "mapping(uint256 => mapping(uint256 => bool))", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(RewardAllocation)49396_storage)": { + "label": "mapping(uint256 => struct IMarketLiquidityRewards.RewardAllocation)", + "numberOfBytes": "32" + }, + "t_struct(RewardAllocation)49396_storage": { + "label": "struct IMarketLiquidityRewards.RewardAllocation", + "members": [ + { + "label": "allocator", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "rewardTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "1" + }, + { + "label": "rewardTokenAmount", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "marketId", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "requiredPrincipalTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "4" + }, + { + "label": "requiredCollateralTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "5" + }, + { + "label": "minimumCollateralPerPrincipalAmount", + "type": "t_uint256", + "offset": 0, + "slot": "6" + }, + { + "label": "rewardPerLoanPrincipalAmount", + "type": "t_uint256", + "offset": 0, + "slot": "7" + }, + { + "label": "bidStartTimeMin", + "type": "t_uint32", + "offset": 0, + "slot": "8" + }, + { + "label": "bidStartTimeMax", + "type": "t_uint32", + "offset": 4, + "slot": "8" + }, + { + "label": "allocationStrategy", + "type": "t_enum(AllocationStrategy)49399", + "offset": 8, + "slot": "8" + } + ], + "numberOfBytes": "288" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint32": { + "label": "uint32", + "numberOfBytes": "4" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + } + } +} diff --git a/packages/contracts/.prettierrc.yml b/packages/contracts/.prettierrc.yml index d73938f23..eb09f6532 100644 --- a/packages/contracts/.prettierrc.yml +++ b/packages/contracts/.prettierrc.yml @@ -1,3 +1,6 @@ +plugins: + - prettier-plugin-solidity +trailingComma: "es5" overrides: - files: - "contracts/**/*.sol" diff --git a/packages/contracts/NEW_NETWORK_DEPLOYMENT_PLAN.md b/packages/contracts/NEW_NETWORK_DEPLOYMENT_PLAN.md new file mode 100644 index 000000000..cb070ab9d --- /dev/null +++ b/packages/contracts/NEW_NETWORK_DEPLOYMENT_PLAN.md @@ -0,0 +1,297 @@ +# New Network Deployment Plan (BSC / Binance Smart Chain) + +Step-by-step guide for deploying Teller Protocol V2 to a new EVM chain. +Uses BSC (chain ID 56) as the concrete example. + +--- + +## Phase 0: Prerequisites & Environment Setup + +### 0.1 — Hardhat Config +- [x] Add network to `NetworkNames` type +- [x] Add RPC URL to `networkUrls` +- [x] Add network to `etherscan.apiKey` +- [x] Add network to `etherscan.customChains` +- [x] Add network entry to `networks` section + +### 0.2 — Environment Variables +Add to `.env`: +``` +BSC_RPC_URL=https://bsc-dataseed1.binance.org +BSCSCAN_VERIFY_API_KEY= +``` + +### 0.3 — Fund Deployer Wallet +- Run `yarn contracts account` to get the deployer address +- Send BNB to the deployer on BSC (estimate ~0.5 BNB for full deployment) + +--- + +## Phase 1: Create Gnosis Safe Multisig + +This must happen **before** contract deployment since deploy scripts reference the Safe address. + +### 1.1 — Create the Safe +1. Go to https://app.safe.global +2. Switch to **BNB Chain** +3. Create a new Safe with the desired signers and threshold +4. Record the Safe address + +### 1.2 — Add Safe address to hardhat config +In `hardhat.config.ts` under `namedAccounts`: +```ts +protocolOwnerSafe: { + // ... existing entries + 56: '', +}, +``` + +### 1.3 — Gnosis Safe helpers +Already configured in `helpers/gnosis-safe-helpers.ts`: +- Chain ID mapping: `'bsc': 56` +- Safe API path: `'bsc': 'bnb'` +- TX service host: `'bsc': 'https://safe-transaction-bsc.safe.global'` + +No changes needed here. + +--- + +## Phase 2: Core Contract Deployment + +Run with: `yarn contracts deploy --network bsc` + +Deployment scripts execute automatically in dependency order via `hardhat-deploy`. +Below is the order and what each phase deploys. + +### 2.1 — Foundation (no dependencies) +| Contract | Deploy Script | Notes | +|---|---|---| +| EscrowVault | `deploy/escrow_vault.ts` | Proxy | +| CollateralEscrowBeacon | `deploy/collateral/escrow_beacon.ts` | Transfers ownership to protocolTimelock | +| MarketRegistry | `deploy/market_registry.ts` | Also deploys TellerAS* contracts | +| MetaForwarder | `deploy/meta_forwarder.ts` | EIP-2771 trusted forwarder | + +### 2.2 — TellerV2 Core +| Contract | Deploy Script | Dependencies | +|---|---|---| +| V2Calculations | `deploy/teller_v2/v2_calculations.ts` | — | +| TellerV2 | `deploy/teller_v2/deploy.ts` | MetaForwarder, V2Calculations | + +### 2.3 — Secondary Contracts +| Contract | Deploy Script | Dependencies | +|---|---|---| +| CollateralManager | `deploy/collateral/manager.ts` | TellerV2, EscrowBeacon | +| LenderManager | `deploy/lender_manager/deploy.ts` | MarketRegistry | +| ReputationManager | `deploy/reputation_manager.ts` | TellerV2 | +| ProtocolPausingManager | `deploy/teller_v2/protocol_pausing_manager.ts` | TellerV2 | + +### 2.4 — TellerV2 Initialization +| Step | Deploy Script | What it does | +|---|---|---| +| Initialize | `deploy/teller_v2/initialize.ts` | Wires all contracts together (fee, registry, collateral mgr, etc.) | + +### 2.5 — Commitment Infrastructure +| Contract | Deploy Script | Dependencies | +|---|---|---| +| LenderCommitmentForwarderAlpha | `deploy/lender_commitment_forwarder/deploy_alpha.ts` | TellerV2, MarketRegistry | +| SmartCommitmentForwarder | `deploy/smart_commitment_forwarder/deploy.ts` | TellerV2, MarketRegistry | + +### 2.6 — Lender Groups (V2) +| Contract | Deploy Script | Dependencies | +|---|---|---| +| LenderGroupBeaconV2 | `deploy/.../lender_commitment_group_v2_beacon.ts` | TellerV2, SmartCommitmentForwarder | +| LenderGroupsFactoryV2 | `deploy/.../lender_groups_factory_v2.ts` | Beacon, SmartCommitmentForwarder | + +### 2.7 — Post-Deploy Ownership Transfer +| Step | Deploy Script | What it does | +|---|---|---| +| Transfer ProxyAdmin | `deploy/default_proxy_admin.ts` | Transfers ProxyAdmin ownership to `protocolTimelock` | +| Transfer TellerV2 | `deploy/teller_v2/transfer_ownership_to_safe.ts` | Transfers TellerV2 ownership to `protocolOwnerSafe` | + +--- + +## Phase 3: Deploy TimelockController + +> **IMPORTANT — This is a two-pass process.** +> The TimelockController deploys during the first `yarn contracts deploy` run, +> but several other scripts (ProxyAdmin transfer, beacon ownership transfers) +> need the timelock address in `namedAccounts.protocolTimelock` to work. +> You must pause after the first run, backfill the address, then re-run. + +### 3.1 — How the Timelock deploys +The script `deploy/admin/timelock_controller.ts` runs automatically as part of +`yarn contracts deploy --network bsc`. It deploys an OpenZeppelin `TimelockController` with: +- **minDelay**: 180 seconds (3 minutes) +- **proposers**: `[protocolOwnerSafe]` (your Gnosis Safe) +- **executors**: `[protocolOwnerSafe]` +- **admin**: `protocolOwnerSafe` + +This means **only your Safe can propose and execute timelocked operations**. + +### 3.2 — After the first deploy run +1. The timelock address will be saved in `deployments/bsc/TimelockController.json` +2. Open that file and copy the `"address"` field +3. Add it to `hardhat.config.ts`: +```ts +protocolTimelock: { + // ... existing entries + 56: '', +}, +``` + +### 3.3 — Re-run deploy to complete ownership transfers +```bash +yarn contracts deploy --network bsc +``` +On this second run, `hardhat-deploy` skips already-deployed contracts (idempotent) +and picks up the scripts that previously failed or were skipped due to the missing +timelock address. These scripts transfer ownership to the timelock: +- `deploy/default_proxy_admin.ts` — transfers **ProxyAdmin** ownership to timelock +- `deploy/collateral/escrow_beacon.ts` — transfers **CollateralEscrowBeacon** ownership to timelock +- `deploy/.../lender_commitment_group_v2_beacon.ts` — transfers **LenderGroupBeaconV2** ownership to timelock + +### 3.4 — Verify ownership transfers +After the second run, confirm on BscScan that: +- ProxyAdmin `owner()` → timelock address +- CollateralEscrowBeacon `owner()` → timelock address +- LenderGroupBeaconV2 `owner()` → timelock address + +--- + +## Phase 4: Ecosystem Contract Addresses + +These are chain-specific external contract addresses required for DeFi integrations. + +### 4.1 — `helpers/ecosystem-contracts-lookup.ts` +Add a `case 'bsc':` block with: + +| Contract | BSC Address | Notes | +|---|---|---| +| WETH9 (WBNB) | `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c` | Wrapped native token | +| Uniswap V3 Factory | Use PancakeSwap V3 factory address | PancakeSwap is the dominant V3 DEX on BSC | +| Swap Router | PancakeSwap V3 SwapRouter | | +| Quoter V2 | PancakeSwap V3 QuoterV2 | | + +**PancakeSwap V3 Addresses (BSC):** +- Factory: `0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865` +- SwapRouter: `0x1b81D678ffb9C0263b24A97847620C99d213eB14` +- QuoterV2: `0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997` + +### 4.2 — Deploy Script Addresses +Update the following deploy scripts with BSC entries: + +**Aave V3 Pool Address Provider** (for flash loan support): +- `deploy/upgrades/03_flash_rollover_g3.ts` +- `deploy/upgrades/09_flash_rollover_g4.ts` +- `deploy/upgrades/11_upgrade_rollover_g5.ts` + +BSC Aave V3 Pool Address Provider: `0xff75B6da14FfbbfD355Daf7a2731456b3562Ba6D` + +**DEX Router / Quoter** (for swap functionality): +- `deploy/lender_commitment_forwarder/extensions/borrow_swap.ts` +- `deploy/lender_commitment_forwarder/extensions/flash_swap_rollover.ts` +- `deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts` + +--- + +## Phase 5: Update Deploy Script Network Lists + +Most deploy scripts have a skip check like: +```ts +deployFn.skip = async (hre) => { + return !hre.network.live || !['polygon', 'mainnet', 'arbitrum', ...].includes(hre.network.name) +} +``` + +Add `'bsc'` to the network arrays in these files: + +### Core Deploys +- [ ] `deploy/proxy/deploy.ts` +- [ ] `deploy/smart_commitment_forwarder/deploy.ts` +- [ ] `deploy/teller_v2/protocol_pausing_manager.ts` +- [ ] `deploy/lender_commitment_forwarder/deploy_alpha.ts` +- [ ] `deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts` +- [ ] `deploy/oracle/mock_hypernative_oracle.ts` + +### Extensions (if deploying flash loans / swaps on BSC) +- [ ] `deploy/lender_commitment_forwarder/extensions/borrow_swap.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/flash_rollover.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/flash_rollover_widget.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/flash_swap_rollover.ts` +- [ ] `deploy/lender_commitment_forwarder/extensions/loan_referral_forwarder.ts` + +### Upgrade Scripts (for future upgrades) +- [ ] `deploy/upgrades/22_upgrade_tellerv2_lender_groups.ts` +- [ ] `deploy/upgrades/26_upgrade_scf_oracle_protection.ts` +- [ ] `deploy/upgrades/30_upgrade_lender_groups_beacon_v2_first_deposit.ts` +- [ ] `deploy/upgrades/31_upgrade_lender_groups_pricing_helper.ts` +- [ ] `deploy/upgrades/34_update_timelock_delay.ts` +- [ ] `deploy/upgrades/35_upgrade_lender_pools_v1.ts` + +--- + +## Phase 6: Verify Contracts + +After deployment, verify all contracts on BscScan: +```bash +yarn contracts verify --network bsc +``` + +Requires `BSCSCAN_VERIFY_API_KEY` in `.env`. +Get an API key from https://bscscan.com/myapikey. + +--- + +## Phase 7: Post-Deployment Validation + +### 7.1 — Run the validation script +```bash +yarn contracts deploy --network bsc --tags validate-deployments +``` + +This checks: +- SmartCommitmentForwarder owner +- LenderGroupsFactory owner +- LenderGroupsBeacon owner +- TellerV2 owner +- EscrowVault configuration +- PausingManager configuration + +### 7.2 — Manual Checks +- [ ] TellerV2 is initialized (marketRegistry, collateralManager, etc. all set) +- [ ] ProxyAdmin owned by `protocolTimelock` +- [ ] TellerV2 owned by `protocolOwnerSafe` +- [ ] SmartCommitmentForwarder owned by `protocolOwnerSafe` +- [ ] CollateralEscrowBeacon owned by `protocolTimelock` +- [ ] Safe can propose and execute transactions via the Safe TX service + +--- + +## Execution Order Summary + +``` +1. Fund deployer wallet with BNB +2. Create Gnosis Safe on BSC → get address +3. Add Safe address to hardhat config (protocolOwnerSafe[56]) +4. Add ecosystem addresses to ecosystem-contracts-lookup.ts +5. Add 'bsc' to all deploy script network lists +6. Run: yarn contracts deploy --network bsc ← FIRST PASS +7. Open deployments/bsc/TimelockController.json → copy the address +8. Add timelock address to hardhat config (protocolTimelock[56]) +9. Run: yarn contracts deploy --network bsc ← SECOND PASS + (completes ownership transfers to timelock) +10. Verify contracts on BscScan +11. Run validation script +12. Manual smoke test via Safe +``` + +--- + +## Rollback + +If deployment fails partway through: +- `hardhat-deploy` is idempotent — re-running `yarn contracts deploy --network bsc` will skip already-deployed contracts +- Deployment artifacts are saved in `deployments/bsc/` +- To redeploy a specific contract, delete its JSON from `deployments/bsc/` and re-run diff --git a/packages/contracts/deploy/admin/timelock_controller.ts b/packages/contracts/deploy/admin/timelock_controller.ts index 51498c7c7..b037a834b 100644 --- a/packages/contracts/deploy/admin/timelock_controller.ts +++ b/packages/contracts/deploy/admin/timelock_controller.ts @@ -59,7 +59,7 @@ deployFn.skip = async (hre) => { // return true; //for now return !( hre.network.live && - [ 'hyperevm' ].includes( + [ 'hyperevm', 'bsc' ].includes( hre.network.name ) ) diff --git a/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts b/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts index d77f060aa..94df187b2 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts @@ -38,7 +38,7 @@ deployFn.tags = [ deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy'] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana' ,'hyperevm'].includes(hre.network.name) + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts index d0eb70822..b815fb850 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts @@ -80,6 +80,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm'].includes(hre.network.name) + return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts index bcd8c5b36..af9b13c08 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts @@ -42,6 +42,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism' ,'katana','hyperevm'].includes(hre.network.name) + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) } export default deployFn \ 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 index 6be48ea39..cb6660432 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts @@ -14,6 +14,6 @@ deployFn.dependencies = [''] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia', 'polygon' , 'base','arbitrum','mainnet','mainnet_live_fork','optimism','katana'].includes(hre.network.name) + return !hre.network.live || !['sepolia', 'polygon' , 'base','arbitrum','mainnet','mainnet_live_fork','optimism','katana','bsc'].includes(hre.network.name) } export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts b/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts index de63aca57..34de8cf63 100644 --- a/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts +++ b/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts @@ -24,6 +24,6 @@ deployFn.id = 'hypernative-oracle-mock:deploy' deployFn.tags = ['hypernative-oracle-mock:deploy'] deployFn.dependencies = [] deployFn.skip = async (hre) => { - return !hre.network.live || ![ 'polygon', 'arbitrum','base','mainnet'].includes(hre.network.name) + return !hre.network.live || !['polygon', 'arbitrum','base','mainnet','bsc'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts b/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts index 0959e183e..baa527d6b 100644 --- a/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts +++ b/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts @@ -20,7 +20,7 @@ deployFn.tags = ['teller-v2', 'uniswap-pricing-helper:deploy'] deployFn.dependencies = [''] deployFn.skip = async (hre) => { - return !hre.network.live || ![ 'polygon', ].includes(hre.network.name) + return !hre.network.live || !['polygon','bsc'].includes(hre.network.name) } export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts b/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts index 35c5da77a..d1b58c04c 100644 --- a/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts +++ b/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts @@ -32,7 +32,7 @@ deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy'] deployFn.skip = async (hre) => { return ( - !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm'].includes(hre.network.name) + !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) ) } export default deployFn diff --git a/packages/contracts/deploy/teller_v2/initialize.ts b/packages/contracts/deploy/teller_v2/initialize.ts index 643b05235..f7343985c 100644 --- a/packages/contracts/deploy/teller_v2/initialize.ts +++ b/packages/contracts/deploy/teller_v2/initialize.ts @@ -11,9 +11,16 @@ const deployFn: DeployFunction = async (hre) => { const marketRegistry = await hre.contracts.get('MarketRegistry') const reputationManager = await hre.contracts.get('ReputationManager') - const lenderCommitmentForwarder = await hre.contracts.get( - 'LenderCommitmentForwarder' - ) + let lenderCommitmentForwarder + try { + lenderCommitmentForwarder = await hre.contracts.get( + 'LenderCommitmentForwarder' + ) + } catch { + lenderCommitmentForwarder = await hre.contracts.get( + 'LenderCommitmentForwarderAlpha' + ) + } const collateralManager = await hre.contracts.get('CollateralManager') const lenderManager = await hre.contracts.get('LenderManager') const escrowVault = await hre.contracts.get('EscrowVault') diff --git a/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts b/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts index 4da718bdf..5ab62246a 100644 --- a/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts +++ b/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts @@ -47,7 +47,7 @@ deployFn.dependencies = ['teller-v2:deploy' ] deployFn.skip = async (hre) => { return ( - !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm'].includes(hre.network.name) + !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) ) } export default deployFn diff --git a/packages/contracts/deployments/bsc/.chainId b/packages/contracts/deployments/bsc/.chainId new file mode 100644 index 000000000..2ebc6516c --- /dev/null +++ b/packages/contracts/deployments/bsc/.chainId @@ -0,0 +1 @@ +56 \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/.latestDeploymentBlock b/packages/contracts/deployments/bsc/.latestDeploymentBlock new file mode 100644 index 000000000..de14b2f0c --- /dev/null +++ b/packages/contracts/deployments/bsc/.latestDeploymentBlock @@ -0,0 +1 @@ +81088820 \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/.migrations.json b/packages/contracts/deployments/bsc/.migrations.json new file mode 100644 index 000000000..817d5553f --- /dev/null +++ b/packages/contracts/deployments/bsc/.migrations.json @@ -0,0 +1,24 @@ +{ + "timelock-controller:deploy": 1771034020, + "collateral:escrow-beacon:deploy": 1771034482, + "meta-forwarder:deploy": 1771034495, + "teller-v2:deploy": 1771034508, + "collateral:manager:deploy": 1771034515, + "escrow-vault:deploy": 1771034523, + "market-registry:deploy": 1771034537, + "reputation-manager:deploy": 1771034546, + "lender-manager:deploy": 1771034554, + "lender-commitment-forwarder:alpha:deploy": 1771035066, + "lender-commitment-forwarder:extensions:flash-swap-rollover:deploy": 1771035115, + "smart-commitment-forwarder:deploy": 1771035616, + "protocol-pausing-manager:deploy": 1771035624, + "teller-v2:init": 1771035625, + "lender-commitment-group-beacon-v2:deploy": 1771035648, + "lender-commitment-group-factory-v2:deploy": 1771035655, + "teller-v2:transfer-ownership-to-safe": 1771035656, + "lender-manager:transfer-ownership": 1771035657, + "liquidity-rewards:deploy": 1771035665, + "hypernative-oracle-mock:deploy": 1771035670, + "validate-deployments": 1771035670, + "default-proxy-admin:transfer": 1771035671 +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/CollateralEscrowBeacon.json b/packages/contracts/deployments/bsc/CollateralEscrowBeacon.json new file mode 100644 index 000000000..467225f37 --- /dev/null +++ b/packages/contracts/deployments/bsc/CollateralEscrowBeacon.json @@ -0,0 +1,350 @@ +{ + "address": "0x0258eAE8bBEf65c523A78705Fe80a82fD75e258d", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "CollateralDeposited", + "inputs": [ + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralWithdrawn", + "inputs": [ + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "address", + "name": "_recipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "bidId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralBalances", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + }, + { + "type": "function", + "name": "depositAsset", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "address", + "name": "_collateralAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "onERC1155BatchReceived", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256[]", + "name": "_ids" + }, + { + "type": "uint256[]", + "name": "_values" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC1155Received", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "id" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC721Received", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdrawDustTokens", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "tokenAddress" + }, + { + "type": "uint256", + "name": "amount" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 2, + "implementation": "0x928685Fd2ce2A3E8909a9f473a85648Ca3689860" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/CollateralManager.json b/packages/contracts/deployments/bsc/CollateralManager.json new file mode 100644 index 000000000..3833d5dd0 --- /dev/null +++ b/packages/contracts/deployments/bsc/CollateralManager.json @@ -0,0 +1,721 @@ +{ + "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "CollateralClaimed", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralCommitted", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralDeposited", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralEscrowDeployed", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "address", + "name": "_collateralEscrow", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralWithdrawn", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + }, + { + "type": "address", + "name": "_recipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "_escrows", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "checkBalances", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validated_" + }, + { + "type": "bool[]", + "name": "checks_" + } + ] + }, + { + "type": "function", + "name": "commitCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "commitCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "tuple", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "deployAndDeposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "amount_" + } + ] + }, + { + "type": "function", + "name": "getCollateralEscrowBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralInfo", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "tuple[]", + "name": "infos_", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ] + }, + { + "type": "function", + "name": "getEscrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralEscrowBeacon" + }, + { + "type": "address", + "name": "_tellerV2" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isBidCollateralBacked", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderClaimCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderClaimCollateralWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralRecipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidateCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_liquidatorAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "onERC1155BatchReceived", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256[]", + "name": "_ids" + }, + { + "type": "uint256[]", + "name": "_values" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC1155Received", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "id" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC721Received", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "revalidateCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "setCollateralEscrowBeacon", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralEscrowBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdrawDustTokens", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_tokenAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "address", + "name": "_recipientAddress" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x08593d76000eb958309a753e65bb7ea708b578dfd6082fb6d66cb9b5351b049d", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/EscrowVault.json b/packages/contracts/deployments/bsc/EscrowVault.json new file mode 100644 index 000000000..34823754a --- /dev/null +++ b/packages/contracts/deployments/bsc/EscrowVault.json @@ -0,0 +1,101 @@ +{ + "address": "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "balances", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + }, + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [] + } + ], + "transactionHash": "0xffd1a811874b826260c992e5e38ff1f29aba29aaf75fbcd5e558dbe766034667", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/HypernativeOracle.json b/packages/contracts/deployments/bsc/HypernativeOracle.json new file mode 100644 index 000000000..ec3236553 --- /dev/null +++ b/packages/contracts/deployments/bsc/HypernativeOracle.json @@ -0,0 +1,737 @@ +{ + "address": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "abi": [ + { + "inputs": [ + { + "internalType": "address", + "name": "_admin", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Allowed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Blacklisted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + } + ], + "name": "ConsumerAdded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + } + ], + "name": "ConsumerRemoved", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Registered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "previousAdminRole", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "newAdminRole", + "type": "bytes32" + } + ], + "name": "RoleAdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleGranted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleRevoked", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "threshold", + "type": "uint256" + } + ], + "name": "TimeThresholdChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Whitelisted", + "type": "event" + }, + { + "inputs": [], + "name": "CONSUMER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DEFAULT_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "OPERATOR_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "consumers", + "type": "address[]" + } + ], + "name": "addConsumers", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "operator", + "type": "address" + } + ], + "name": "addOperator", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "allow", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "blacklist", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_newThreshold", + "type": "uint256" + } + ], + "name": "changeTimeThreshold", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + } + ], + "name": "getRoleAdmin", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "grantRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "hasRole", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "isBlacklistedAccount", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_origin", + "type": "address" + }, + { + "internalType": "address", + "name": "_sender", + "type": "address" + } + ], + "name": "isBlacklistedContext", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "isTimeExceeded", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "register", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "registerStrict", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "renounceRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "consumers", + "type": "address[]" + } + ], + "name": "revokeConsumers", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "revokeRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes4", + "name": "interfaceId", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "whitelist", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x0c1256e4df72aa1e3938bbc7d1518cd4dc856fd3de29b76aa0dac7ed8b1b2fd7", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "transactionIndex": 44, + "gasUsed": "1369961", + "logsBloom": "0x00000044000000000002000040000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000020000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000200000000000000000000000000000000000000100000000000020000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x62ecd091bb3de518f6a7c5f68e460760942ce0fd55677029d59a53d27d1faa0e", + "transactionHash": "0x0c1256e4df72aa1e3938bbc7d1518cd4dc856fd3de29b76aa0dac7ed8b1b2fd7", + "logs": [ + { + "transactionIndex": 44, + "blockNumber": 81088820, + "transactionHash": "0x0c1256e4df72aa1e3938bbc7d1518cd4dc856fd3de29b76aa0dac7ed8b1b2fd7", + "address": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 164, + "blockHash": "0x62ecd091bb3de518f6a7c5f68e460760942ce0fd55677029d59a53d27d1faa0e" + } + ], + "blockNumber": 81088820, + "cumulativeGasUsed": "7497158", + "status": 1, + "byzantium": true + }, + "args": [ + "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_admin\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Allowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Blacklisted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"}],\"name\":\"ConsumerAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"}],\"name\":\"ConsumerRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Registered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"threshold\",\"type\":\"uint256\"}],\"name\":\"TimeThresholdChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Whitelisted\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CONSUMER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OPERATOR_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"consumers\",\"type\":\"address[]\"}],\"name\":\"addConsumers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"addOperator\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"allow\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"blacklist\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_newThreshold\",\"type\":\"uint256\"}],\"name\":\"changeTimeThreshold\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"isBlacklistedAccount\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_origin\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_sender\",\"type\":\"address\"}],\"name\":\"isBlacklistedContext\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"isTimeExceeded\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"register\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"registerStrict\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"consumers\",\"type\":\"address[]\"}],\"name\":\"revokeConsumers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"revokeOperator\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"whitelist\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"changeTimeThreshold(uint256)\":{\"details\":\"Admin only function, can be used to block any interaction with the protocol, meassured in seconds\"},\"getRoleAdmin(bytes32)\":{\"details\":\"Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}.\"},\"grantRole(bytes32,address)\":{\"details\":\"Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event.\"},\"hasRole(bytes32,address)\":{\"details\":\"Returns `true` if `account` has been granted `role`.\"},\"renounceRole(bytes32,address)\":{\"details\":\"Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event.\"},\"revokeRole(bytes32,address)\":{\"details\":\"Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event.\"},\"supportsInterface(bytes4)\":{\"details\":\"See {IERC165-supportsInterface}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/oracleprotection/HypernativeOracle.sol\":\"HypernativeOracle\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts/access/AccessControl.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IAccessControl.sol\\\";\\nimport \\\"../utils/Context.sol\\\";\\nimport \\\"../utils/Strings.sol\\\";\\nimport \\\"../utils/introspection/ERC165.sol\\\";\\n\\n/**\\n * @dev Contract module that allows children to implement role-based access\\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\\n * members except through off-chain means by accessing the contract event logs. Some\\n * applications may benefit from on-chain enumerability, for those cases see\\n * {AccessControlEnumerable}.\\n *\\n * Roles are referred to by their `bytes32` identifier. These should be exposed\\n * in the external API and be unique. The best way to achieve this is by\\n * using `public constant` hash digests:\\n *\\n * ```\\n * bytes32 public constant MY_ROLE = keccak256(\\\"MY_ROLE\\\");\\n * ```\\n *\\n * Roles can be used to represent a set of permissions. To restrict access to a\\n * function call, use {hasRole}:\\n *\\n * ```\\n * function foo() public {\\n * require(hasRole(MY_ROLE, msg.sender));\\n * ...\\n * }\\n * ```\\n *\\n * Roles can be granted and revoked dynamically via the {grantRole} and\\n * {revokeRole} functions. Each role has an associated admin role, and only\\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\\n *\\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\\n * that only accounts with this role will be able to grant or revoke other\\n * roles. More complex role relationships can be created by using\\n * {_setRoleAdmin}.\\n *\\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\\n * grant and revoke this role. Extra precautions should be taken to secure\\n * accounts that have been granted it.\\n */\\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\\n struct RoleData {\\n mapping(address => bool) members;\\n bytes32 adminRole;\\n }\\n\\n mapping(bytes32 => RoleData) private _roles;\\n\\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\\n\\n /**\\n * @dev Modifier that checks that an account has a specific role. Reverts\\n * with a standardized message including the required role.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n *\\n * _Available since v4.1._\\n */\\n modifier onlyRole(bytes32 role) {\\n _checkRole(role);\\n _;\\n }\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\\n return _roles[role].members[account];\\n }\\n\\n /**\\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\\n * Overriding this function changes the behavior of the {onlyRole} modifier.\\n *\\n * Format of the revert message is described in {_checkRole}.\\n *\\n * _Available since v4.6._\\n */\\n function _checkRole(bytes32 role) internal view virtual {\\n _checkRole(role, _msgSender());\\n }\\n\\n /**\\n * @dev Revert with a standard message if `account` is missing `role`.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n */\\n function _checkRole(bytes32 role, address account) internal view virtual {\\n if (!hasRole(role, account)) {\\n revert(\\n string(\\n abi.encodePacked(\\n \\\"AccessControl: account \\\",\\n Strings.toHexString(account),\\n \\\" is missing role \\\",\\n Strings.toHexString(uint256(role), 32)\\n )\\n )\\n );\\n }\\n }\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\\n return _roles[role].adminRole;\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function renounceRole(bytes32 role, address account) public virtual override {\\n require(account == _msgSender(), \\\"AccessControl: can only renounce roles for self\\\");\\n\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event. Note that unlike {grantRole}, this function doesn't perform any\\n * checks on the calling account.\\n *\\n * May emit a {RoleGranted} event.\\n *\\n * [WARNING]\\n * ====\\n * This function should only be called from the constructor when setting\\n * up the initial roles for the system.\\n *\\n * Using this function in any other way is effectively circumventing the admin\\n * system imposed by {AccessControl}.\\n * ====\\n *\\n * NOTE: This function is deprecated in favor of {_grantRole}.\\n */\\n function _setupRole(bytes32 role, address account) internal virtual {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Sets `adminRole` as ``role``'s admin role.\\n *\\n * Emits a {RoleAdminChanged} event.\\n */\\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\\n bytes32 previousAdminRole = getRoleAdmin(role);\\n _roles[role].adminRole = adminRole;\\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function _grantRole(bytes32 role, address account) internal virtual {\\n if (!hasRole(role, account)) {\\n _roles[role].members[account] = true;\\n emit RoleGranted(role, account, _msgSender());\\n }\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function _revokeRole(bytes32 role, address account) internal virtual {\\n if (hasRole(role, account)) {\\n _roles[role].members[account] = false;\\n emit RoleRevoked(role, account, _msgSender());\\n }\\n }\\n}\\n\",\"keccak256\":\"0x67e3daf189111d6d5b0464ed09cf9f0605a22c4b965a7fcecd707101faff008a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/access/IAccessControl.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev External interface of AccessControl declared to support ERC165 detection.\\n */\\ninterface IAccessControl {\\n /**\\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\\n *\\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\\n * {RoleAdminChanged} not being emitted signaling this.\\n *\\n * _Available since v3.1._\\n */\\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\\n\\n /**\\n * @dev Emitted when `account` is granted `role`.\\n *\\n * `sender` is the account that originated the contract call, an admin role\\n * bearer except when using {AccessControl-_setupRole}.\\n */\\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\\n\\n /**\\n * @dev Emitted when `account` is revoked `role`.\\n *\\n * `sender` is the account that originated the contract call:\\n * - if using `revokeRole`, it is the admin role bearer\\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\\n */\\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account) external view returns (bool);\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function grantRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function revokeRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been granted `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n */\\n function renounceRole(bytes32 role, address account) external;\\n}\\n\",\"keccak256\":\"0x59ce320a585d7e1f163cd70390a0ef2ff9cec832e2aa544293a00692465a7a57\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xe2e337e6dde9ef6b680e07338c493ebea1b5fd09b43424112868e9cc1706bca7\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xa4d1d62251f8574deb032a35fc948386a9b4de74b812d4f545a1ac120486b48a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/introspection/ERC165.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IERC165.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC165} interface.\\n *\\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\\n * for the additional interface id that will be supported. For example:\\n *\\n * ```solidity\\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\\n * }\\n * ```\\n *\\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\\n */\\nabstract contract ERC165 is IERC165 {\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return interfaceId == type(IERC165).interfaceId;\\n }\\n}\\n\",\"keccak256\":\"0xd10975de010d89fd1c78dc5e8a9a7e7f496198085c151648f20cba166b32582b\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\\n /**\\n * @dev Returns true if this contract implements the interface defined by\\n * `interfaceId`. See the corresponding\\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\\n * to learn more about how these ids are created.\\n *\\n * This function call must use less than 30 000 gas.\\n */\\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\\n}\\n\",\"keccak256\":\"0x447a5f3ddc18419d41ff92b3773fb86471b1db25773e07f877f548918a185bf1\",\"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/oracleprotection/HypernativeOracle.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport {AccessControl} from \\\"@openzeppelin/contracts/access/AccessControl.sol\\\";\\n\\ncontract HypernativeOracle is AccessControl {\\n struct OracleRecord {\\n uint256 registrationTime;\\n bool isPotentialRisk;\\n }\\n\\n bytes32 public constant OPERATOR_ROLE = keccak256(\\\"OPERATOR_ROLE\\\");\\n bytes32 public constant CONSUMER_ROLE = keccak256(\\\"CONSUMER_ROLE\\\");\\n uint256 internal threshold = 2 minutes;\\n\\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\\n \\n event ConsumerAdded(address consumer);\\n event ConsumerRemoved(address consumer);\\n event Registered(address consumer, address account);\\n event Whitelisted(bytes32[] hashedAccounts);\\n event Allowed(bytes32[] hashedAccounts);\\n event Blacklisted(bytes32[] hashedAccounts);\\n event TimeThresholdChanged(uint256 threshold);\\n\\n modifier onlyAdmin() {\\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \\\"Hypernative Oracle error: admin required\\\");\\n _;\\n }\\n\\n modifier onlyOperator() {\\n require(hasRole(OPERATOR_ROLE, msg.sender), \\\"Hypernative Oracle error: operator required\\\");\\n _;\\n }\\n\\n modifier onlyConsumer {\\n require(hasRole(CONSUMER_ROLE, msg.sender), \\\"Hypernative Oracle error: consumer required\\\");\\n _;\\n }\\n\\n constructor(address _admin) {\\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\\n }\\n\\n function register(address _account) external onlyConsumer() {\\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \\\"Account already registered\\\");\\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\\n emit Registered(msg.sender, _account);\\n }\\n\\n function registerStrict(address _account) external onlyConsumer() {\\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \\\"Account already registered\\\");\\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\\n emit Registered(msg.sender, _account);\\n }\\n\\n // **\\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\\n }\\n emit Whitelisted(hashedAccounts);\\n }\\n\\n // **\\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\\n }\\n emit Blacklisted(hashedAccounts);\\n }\\n\\n // **\\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\\n }\\n emit Allowed(hashedAccounts);\\n }\\n\\n /**\\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\\n */\\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\\n require(_newThreshold >= 2 minutes, \\\"Threshold must be greater than 2 minutes\\\");\\n threshold = _newThreshold;\\n emit TimeThresholdChanged(threshold);\\n }\\n\\n function addConsumers(address[] memory consumers) public onlyAdmin() {\\n for (uint256 i; i < consumers.length; i++) {\\n _grantRole(CONSUMER_ROLE, consumers[i]);\\n emit ConsumerAdded(consumers[i]);\\n }\\n }\\n\\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\\n for (uint256 i; i < consumers.length; i++) {\\n _revokeRole(CONSUMER_ROLE, consumers[i]);\\n emit ConsumerRemoved(consumers[i]);\\n }\\n }\\n\\n function addOperator(address operator) public onlyAdmin() {\\n _grantRole(OPERATOR_ROLE, operator);\\n }\\n\\n function revokeOperator(address operator) public onlyAdmin() {\\n _revokeRole(OPERATOR_ROLE, operator);\\n }\\n\\n function changeAdmin(address _newAdmin) public onlyAdmin() {\\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\\n }\\n\\n //if true, the account has been registered for two minutes \\n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \\\"Account not registered\\\");\\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\\n }\\n\\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\\n }\\n\\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n return accountHashToRecord[hashedAccount].isPotentialRisk;\\n }\\n}\\n\",\"keccak256\":\"0x7c2eecadae47637f892b06431668c08e08c81911517b8d43ee1d814675512464\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052607860015534801561001557600080fd5b506040516200180938038062001809833981016040819052610036916100e6565b610041600082610047565b50610116565b6000828152602081815260408083206001600160a01b038516845290915290205460ff166100e2576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556100a13390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b6000602082840312156100f857600080fd5b81516001600160a01b038116811461010f57600080fd5b9392505050565b6116e380620001266000396000f3fe608060405234801561001057600080fd5b506004361061014d5760003560e01c80635fab577a116100c3578063a75413b41161007c578063a75413b4146102c1578063d547741f146102d4578063d7b8a621146102e7578063f5b541a6146102fa578063f6985cc31461030f578063fad8b32a1461032257600080fd5b80635fab577a1461025a5780636cffbed31461026d5780638f2839701461028057806391d14854146102935780639870d7fe146102a6578063a217fddf146102b957600080fd5b806330c7992c1161011557806330c7992c146101e657806336568abe146101f95780633b9f83831461020c57806342c18b831461021f5780634420e486146102325780634bc02da61461024557600080fd5b806301ffc9a7146101525780630d7b87e21461017a5780631c1efe9e1461018f578063248a9ca3146101a25780632f2ff15d146101d3575b600080fd5b61016561016036600461118d565b610335565b60405190151581526020015b60405180910390f35b61018d6101883660046111b7565b61036c565b005b61018d61019d366004611259565b61044c565b6101c56101b036600461131e565b60009081526020819052604090206001015490565b604051908152602001610171565b61018d6101e1366004611337565b610525565b61018d6101f4366004611363565b61054f565b61018d610207366004611337565b610670565b61018d61021a3660046111b7565b6106ea565b61018d61022d3660046111b7565b6107e9565b61018d610240366004611363565b6108b4565b6101c560008051602061166e83398151915281565b61018d61026836600461131e565b6109c5565b61016561027b366004611363565b610a89565b61018d61028e366004611363565b610b67565b6101656102a1366004611337565b610ba7565b61018d6102b4366004611363565b610bd0565b6101c5600081565b61018d6102cf366004611259565b610c0f565b61018d6102e2366004611337565b610ce4565b6101656102f536600461137e565b610d09565b6101c560008051602061168e83398151915281565b61016561031d366004611363565b610dd4565b61018d610330366004611363565b610e51565b60006001600160e01b03198216637965db0b60e01b148061036657506301ffc9a760e01b6001600160e01b03198316145b92915050565b61038460008051602061168e83398151915233610ba7565b6103a95760405162461bcd60e51b81526004016103a0906113a8565b60405180910390fd5b60005b8181101561040e576000600260008585858181106103cc576103cc6113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806104069061141f565b9150506103ac565b507f9e4e4c1f160b3b53eb86440bbe855c3fc2acdd15761379368f16cf58057c5568828260405161044092919061143a565b60405180910390a15050565b610457600033610ba7565b6104735760405162461bcd60e51b81526004016103a090611476565b60005b8151811015610521576104b060008051602061166e8339815191528383815181106104a3576104a36113f3565b6020026020010151610e8c565b7fe3f5ed5f263f1f01764a96edfc7d025f511ec5f7d180e8816908b78bcf74f0988282815181106104e3576104e36113f3565b602002602001015160405161050791906001600160a01b0391909116815260200190565b60405180910390a1806105198161141f565b915050610476565b5050565b60008281526020819052604090206001015461054081610ef1565b61054a8383610efb565b505050565b61056760008051602061166e83398151915233610ba7565b6105835760405162461bcd60e51b81526004016103a0906114be565b60008130604051602001610598929190611509565b60408051601f198184030181529181528151602092830120600081815260029093529120549091501561060d5760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b6000818152600260209081526040918290204281556001908101805460ff1916909117905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6001600160a01b03811633146106e05760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016103a0565b6105218282610e8c565b61070260008051602061168e83398151915233610ba7565b61071e5760405162461bcd60e51b81526004016103a0906113a8565b60005b818110156107b757600160026000858585818110610741576107416113f3565b90506020020135815260200190815260200160002060000181905550600060026000858585818110610775576107756113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806107af9061141f565b915050610721565b507f3e087f3011cfcdd221d882f74ea094cde44bd2090a2c8ef9bbbcd45162664042828260405161044092919061143a565b61080160008051602061168e83398151915233610ba7565b61081d5760405162461bcd60e51b81526004016103a0906113a8565b60005b8181101561088257600160026000858585818110610840576108406113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff021916908315150217905550808061087a9061141f565b915050610820565b507f6c2a1a20729e85f030b21b1d3838b795aca2b8bd26d4f5ad4134128bc1734222828260405161044092919061143a565b6108cc60008051602061166e83398151915233610ba7565b6108e85760405162461bcd60e51b81526004016103a0906114be565b600081306040516020016108fd929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150156109725760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b60008181526002602090815260409182902042905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6109d0600033610ba7565b6109ec5760405162461bcd60e51b81526004016103a090611476565b6078811015610a4e5760405162461bcd60e51b815260206004820152602860248201527f5468726573686f6c64206d7573742062652067726561746572207468616e2032604482015267206d696e7574657360c01b60648201526084016103a0565b60018190556040518181527f99d47da2054f02d98111bd426aeb7d28d2d2b8d77ad536b453f1b19f16fd44a39060200160405180910390a150565b6000610aa360008051602061166e83398151915233610ba7565b610abf5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610ad4929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150610b415760405162461bcd60e51b81526020600482015260166024820152751058d8dbdd5b9d081b9bdd081c9959da5cdd195c995960521b60448201526064016103a0565b600154600082815260026020526040902054610b5d9042611530565b119150505b919050565b610b72600033610ba7565b610b8e5760405162461bcd60e51b81526004016103a090611476565b610b99600082610efb565b610ba4600033610e8c565b50565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b610bdb600033610ba7565b610bf75760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e83398151915282610efb565b610c1a600033610ba7565b610c365760405162461bcd60e51b81526004016103a090611476565b60005b815181101561052157610c7360008051602061166e833981519152838381518110610c6657610c666113f3565b6020026020010151610efb565b7f28b26e7a3d20aedbc5f8f2ebf7da671c0491723a2b78f47a097b0e46dee07142828281518110610ca657610ca66113f3565b6020026020010151604051610cca91906001600160a01b0391909116815260200190565b60405180910390a180610cdc8161141f565b915050610c39565b600082815260208190526040902060010154610cff81610ef1565b61054a8383610e8c565b6000610d2360008051602061166e83398151915233610ba7565b610d3f5760405162461bcd60e51b81526004016103a0906114be565b60008330604051602001610d54929190611509565b60405160208183030381529060405280519060200120905060008330604051602001610d81929190611509565b60408051601f1981840301815291815281516020928301206000858152600290935291206001015490915060ff1680610dcb575060008181526002602052604090206001015460ff165b95945050505050565b6000610dee60008051602061166e83398151915233610ba7565b610e0a5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610e1f929190611509565b60408051808303601f1901815291815281516020928301206000908152600290925290206001015460ff169392505050565b610e5c600033610ba7565b610e785760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e833981519152825b610e968282610ba7565b15610521576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610ba48133610f7f565b610f058282610ba7565b610521576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f3b3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610f898282610ba7565b61052157610f9681610fd8565b610fa1836020610fea565b604051602001610fb2929190611577565b60408051601f198184030181529082905262461bcd60e51b82526103a0916004016115ec565b60606103666001600160a01b03831660145b60606000610ff983600261161f565b61100490600261163e565b67ffffffffffffffff81111561101c5761101c61122c565b6040519080825280601f01601f191660200182016040528015611046576020820181803683370190505b509050600360fc1b81600081518110611061576110616113f3565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611090576110906113f3565b60200101906001600160f81b031916908160001a90535060006110b484600261161f565b6110bf90600161163e565b90505b6001811115611137576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106110f3576110f36113f3565b1a60f81b828281518110611109576111096113f3565b60200101906001600160f81b031916908160001a90535060049490941c9361113081611656565b90506110c2565b5083156111865760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016103a0565b9392505050565b60006020828403121561119f57600080fd5b81356001600160e01b03198116811461118657600080fd5b600080602083850312156111ca57600080fd5b823567ffffffffffffffff808211156111e257600080fd5b818501915085601f8301126111f657600080fd5b81358181111561120557600080fd5b8660208260051b850101111561121a57600080fd5b60209290920196919550909350505050565b634e487b7160e01b600052604160045260246000fd5b80356001600160a01b0381168114610b6257600080fd5b6000602080838503121561126c57600080fd5b823567ffffffffffffffff8082111561128457600080fd5b818501915085601f83011261129857600080fd5b8135818111156112aa576112aa61122c565b8060051b604051601f19603f830116810181811085821117156112cf576112cf61122c565b6040529182528482019250838101850191888311156112ed57600080fd5b938501935b828510156113125761130385611242565b845293850193928501926112f2565b98975050505050505050565b60006020828403121561133057600080fd5b5035919050565b6000806040838503121561134a57600080fd5b8235915061135a60208401611242565b90509250929050565b60006020828403121561137557600080fd5b61118682611242565b6000806040838503121561139157600080fd5b61139a83611242565b915061135a60208401611242565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a206f706572617460408201526a1bdc881c995c5d5a5c995960aa1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060001982141561143357611433611409565b5060010190565b6020808252810182905260006001600160fb1b0383111561145a57600080fd5b8260051b80856040850137600092016040019182525092915050565b60208082526028908201527f48797065726e6174697665204f7261636c65206572726f723a2061646d696e206040820152671c995c5d5a5c995960c21b606082015260800190565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a20636f6e73756d60408201526a195c881c995c5d5a5c995960aa1b606082015260800190565b6bffffffffffffffffffffffff19606093841b811682529190921b16601482015260280190565b60008282101561154257611542611409565b500390565b60005b8381101561156257818101518382015260200161154a565b83811115611571576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516115af816017850160208801611547565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516115e0816028840160208801611547565b01602801949350505050565b602081526000825180602084015261160b816040850160208701611547565b601f01601f19169190910160400192915050565b600081600019048311821515161561163957611639611409565b500290565b6000821982111561165157611651611409565b500190565b60008161166557611665611409565b50600019019056fe9d56108290ea0bc9c5c59c3ad357dca9d1b29ed7f3ae1443bef2fa2159bdf5e897667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929a26469706673582212202209b92945b24aecf31433a99250e9597a1896fe78c53ca40e585638df2ca28c64736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061014d5760003560e01c80635fab577a116100c3578063a75413b41161007c578063a75413b4146102c1578063d547741f146102d4578063d7b8a621146102e7578063f5b541a6146102fa578063f6985cc31461030f578063fad8b32a1461032257600080fd5b80635fab577a1461025a5780636cffbed31461026d5780638f2839701461028057806391d14854146102935780639870d7fe146102a6578063a217fddf146102b957600080fd5b806330c7992c1161011557806330c7992c146101e657806336568abe146101f95780633b9f83831461020c57806342c18b831461021f5780634420e486146102325780634bc02da61461024557600080fd5b806301ffc9a7146101525780630d7b87e21461017a5780631c1efe9e1461018f578063248a9ca3146101a25780632f2ff15d146101d3575b600080fd5b61016561016036600461118d565b610335565b60405190151581526020015b60405180910390f35b61018d6101883660046111b7565b61036c565b005b61018d61019d366004611259565b61044c565b6101c56101b036600461131e565b60009081526020819052604090206001015490565b604051908152602001610171565b61018d6101e1366004611337565b610525565b61018d6101f4366004611363565b61054f565b61018d610207366004611337565b610670565b61018d61021a3660046111b7565b6106ea565b61018d61022d3660046111b7565b6107e9565b61018d610240366004611363565b6108b4565b6101c560008051602061166e83398151915281565b61018d61026836600461131e565b6109c5565b61016561027b366004611363565b610a89565b61018d61028e366004611363565b610b67565b6101656102a1366004611337565b610ba7565b61018d6102b4366004611363565b610bd0565b6101c5600081565b61018d6102cf366004611259565b610c0f565b61018d6102e2366004611337565b610ce4565b6101656102f536600461137e565b610d09565b6101c560008051602061168e83398151915281565b61016561031d366004611363565b610dd4565b61018d610330366004611363565b610e51565b60006001600160e01b03198216637965db0b60e01b148061036657506301ffc9a760e01b6001600160e01b03198316145b92915050565b61038460008051602061168e83398151915233610ba7565b6103a95760405162461bcd60e51b81526004016103a0906113a8565b60405180910390fd5b60005b8181101561040e576000600260008585858181106103cc576103cc6113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806104069061141f565b9150506103ac565b507f9e4e4c1f160b3b53eb86440bbe855c3fc2acdd15761379368f16cf58057c5568828260405161044092919061143a565b60405180910390a15050565b610457600033610ba7565b6104735760405162461bcd60e51b81526004016103a090611476565b60005b8151811015610521576104b060008051602061166e8339815191528383815181106104a3576104a36113f3565b6020026020010151610e8c565b7fe3f5ed5f263f1f01764a96edfc7d025f511ec5f7d180e8816908b78bcf74f0988282815181106104e3576104e36113f3565b602002602001015160405161050791906001600160a01b0391909116815260200190565b60405180910390a1806105198161141f565b915050610476565b5050565b60008281526020819052604090206001015461054081610ef1565b61054a8383610efb565b505050565b61056760008051602061166e83398151915233610ba7565b6105835760405162461bcd60e51b81526004016103a0906114be565b60008130604051602001610598929190611509565b60408051601f198184030181529181528151602092830120600081815260029093529120549091501561060d5760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b6000818152600260209081526040918290204281556001908101805460ff1916909117905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6001600160a01b03811633146106e05760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016103a0565b6105218282610e8c565b61070260008051602061168e83398151915233610ba7565b61071e5760405162461bcd60e51b81526004016103a0906113a8565b60005b818110156107b757600160026000858585818110610741576107416113f3565b90506020020135815260200190815260200160002060000181905550600060026000858585818110610775576107756113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806107af9061141f565b915050610721565b507f3e087f3011cfcdd221d882f74ea094cde44bd2090a2c8ef9bbbcd45162664042828260405161044092919061143a565b61080160008051602061168e83398151915233610ba7565b61081d5760405162461bcd60e51b81526004016103a0906113a8565b60005b8181101561088257600160026000858585818110610840576108406113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff021916908315150217905550808061087a9061141f565b915050610820565b507f6c2a1a20729e85f030b21b1d3838b795aca2b8bd26d4f5ad4134128bc1734222828260405161044092919061143a565b6108cc60008051602061166e83398151915233610ba7565b6108e85760405162461bcd60e51b81526004016103a0906114be565b600081306040516020016108fd929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150156109725760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b60008181526002602090815260409182902042905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6109d0600033610ba7565b6109ec5760405162461bcd60e51b81526004016103a090611476565b6078811015610a4e5760405162461bcd60e51b815260206004820152602860248201527f5468726573686f6c64206d7573742062652067726561746572207468616e2032604482015267206d696e7574657360c01b60648201526084016103a0565b60018190556040518181527f99d47da2054f02d98111bd426aeb7d28d2d2b8d77ad536b453f1b19f16fd44a39060200160405180910390a150565b6000610aa360008051602061166e83398151915233610ba7565b610abf5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610ad4929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150610b415760405162461bcd60e51b81526020600482015260166024820152751058d8dbdd5b9d081b9bdd081c9959da5cdd195c995960521b60448201526064016103a0565b600154600082815260026020526040902054610b5d9042611530565b119150505b919050565b610b72600033610ba7565b610b8e5760405162461bcd60e51b81526004016103a090611476565b610b99600082610efb565b610ba4600033610e8c565b50565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b610bdb600033610ba7565b610bf75760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e83398151915282610efb565b610c1a600033610ba7565b610c365760405162461bcd60e51b81526004016103a090611476565b60005b815181101561052157610c7360008051602061166e833981519152838381518110610c6657610c666113f3565b6020026020010151610efb565b7f28b26e7a3d20aedbc5f8f2ebf7da671c0491723a2b78f47a097b0e46dee07142828281518110610ca657610ca66113f3565b6020026020010151604051610cca91906001600160a01b0391909116815260200190565b60405180910390a180610cdc8161141f565b915050610c39565b600082815260208190526040902060010154610cff81610ef1565b61054a8383610e8c565b6000610d2360008051602061166e83398151915233610ba7565b610d3f5760405162461bcd60e51b81526004016103a0906114be565b60008330604051602001610d54929190611509565b60405160208183030381529060405280519060200120905060008330604051602001610d81929190611509565b60408051601f1981840301815291815281516020928301206000858152600290935291206001015490915060ff1680610dcb575060008181526002602052604090206001015460ff165b95945050505050565b6000610dee60008051602061166e83398151915233610ba7565b610e0a5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610e1f929190611509565b60408051808303601f1901815291815281516020928301206000908152600290925290206001015460ff169392505050565b610e5c600033610ba7565b610e785760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e833981519152825b610e968282610ba7565b15610521576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610ba48133610f7f565b610f058282610ba7565b610521576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f3b3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610f898282610ba7565b61052157610f9681610fd8565b610fa1836020610fea565b604051602001610fb2929190611577565b60408051601f198184030181529082905262461bcd60e51b82526103a0916004016115ec565b60606103666001600160a01b03831660145b60606000610ff983600261161f565b61100490600261163e565b67ffffffffffffffff81111561101c5761101c61122c565b6040519080825280601f01601f191660200182016040528015611046576020820181803683370190505b509050600360fc1b81600081518110611061576110616113f3565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611090576110906113f3565b60200101906001600160f81b031916908160001a90535060006110b484600261161f565b6110bf90600161163e565b90505b6001811115611137576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106110f3576110f36113f3565b1a60f81b828281518110611109576111096113f3565b60200101906001600160f81b031916908160001a90535060049490941c9361113081611656565b90506110c2565b5083156111865760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016103a0565b9392505050565b60006020828403121561119f57600080fd5b81356001600160e01b03198116811461118657600080fd5b600080602083850312156111ca57600080fd5b823567ffffffffffffffff808211156111e257600080fd5b818501915085601f8301126111f657600080fd5b81358181111561120557600080fd5b8660208260051b850101111561121a57600080fd5b60209290920196919550909350505050565b634e487b7160e01b600052604160045260246000fd5b80356001600160a01b0381168114610b6257600080fd5b6000602080838503121561126c57600080fd5b823567ffffffffffffffff8082111561128457600080fd5b818501915085601f83011261129857600080fd5b8135818111156112aa576112aa61122c565b8060051b604051601f19603f830116810181811085821117156112cf576112cf61122c565b6040529182528482019250838101850191888311156112ed57600080fd5b938501935b828510156113125761130385611242565b845293850193928501926112f2565b98975050505050505050565b60006020828403121561133057600080fd5b5035919050565b6000806040838503121561134a57600080fd5b8235915061135a60208401611242565b90509250929050565b60006020828403121561137557600080fd5b61118682611242565b6000806040838503121561139157600080fd5b61139a83611242565b915061135a60208401611242565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a206f706572617460408201526a1bdc881c995c5d5a5c995960aa1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060001982141561143357611433611409565b5060010190565b6020808252810182905260006001600160fb1b0383111561145a57600080fd5b8260051b80856040850137600092016040019182525092915050565b60208082526028908201527f48797065726e6174697665204f7261636c65206572726f723a2061646d696e206040820152671c995c5d5a5c995960c21b606082015260800190565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a20636f6e73756d60408201526a195c881c995c5d5a5c995960aa1b606082015260800190565b6bffffffffffffffffffffffff19606093841b811682529190921b16601482015260280190565b60008282101561154257611542611409565b500390565b60005b8381101561156257818101518382015260200161154a565b83811115611571576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516115af816017850160208801611547565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516115e0816028840160208801611547565b01602801949350505050565b602081526000825180602084015261160b816040850160208701611547565b601f01601f19169190910160400192915050565b600081600019048311821515161561163957611639611409565b500290565b6000821982111561165157611651611409565b500190565b60008161166557611665611409565b50600019019056fe9d56108290ea0bc9c5c59c3ad357dca9d1b29ed7f3ae1443bef2fa2159bdf5e897667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929a26469706673582212202209b92945b24aecf31433a99250e9597a1896fe78c53ca40e585638df2ca28c64736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "changeTimeThreshold(uint256)": { + "details": "Admin only function, can be used to block any interaction with the protocol, meassured in seconds" + }, + "getRoleAdmin(bytes32)": { + "details": "Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}." + }, + "grantRole(bytes32,address)": { + "details": "Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event." + }, + "hasRole(bytes32,address)": { + "details": "Returns `true` if `account` has been granted `role`." + }, + "renounceRole(bytes32,address)": { + "details": "Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event." + }, + "revokeRole(bytes32,address)": { + "details": "Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event." + }, + "supportsInterface(bytes4)": { + "details": "See {IERC165-supportsInterface}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 6133, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "_roles", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(RoleData)6128_storage)" + }, + { + "astId": 69724, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "threshold", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 69729, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "accountHashToRecord", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_bytes32,t_struct(OracleRecord)69711_storage)" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => bool)", + "numberOfBytes": "32", + "value": "t_bool" + }, + "t_mapping(t_bytes32,t_struct(OracleRecord)69711_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct HypernativeOracle.OracleRecord)", + "numberOfBytes": "32", + "value": "t_struct(OracleRecord)69711_storage" + }, + "t_mapping(t_bytes32,t_struct(RoleData)6128_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct AccessControl.RoleData)", + "numberOfBytes": "32", + "value": "t_struct(RoleData)6128_storage" + }, + "t_struct(OracleRecord)69711_storage": { + "encoding": "inplace", + "label": "struct HypernativeOracle.OracleRecord", + "members": [ + { + "astId": 69708, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "registrationTime", + "offset": 0, + "slot": "0", + "type": "t_uint256" + }, + { + "astId": 69710, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "isPotentialRisk", + "offset": 0, + "slot": "1", + "type": "t_bool" + } + ], + "numberOfBytes": "64" + }, + "t_struct(RoleData)6128_storage": { + "encoding": "inplace", + "label": "struct AccessControl.RoleData", + "members": [ + { + "astId": 6125, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "members", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_bool)" + }, + { + "astId": 6127, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "adminRole", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/LenderCommitmentForwarderAlpha.json b/packages/contracts/deployments/bsc/LenderCommitmentForwarderAlpha.json new file mode 100644 index 000000000..8ea80424e --- /dev/null +++ b/packages/contracts/deployments/bsc/LenderCommitmentForwarderAlpha.json @@ -0,0 +1,1189 @@ +{ + "address": "0xfDDcEc68cfa40c38Faf05F918484fC416a221BFF", + "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": "getUniswapPriceRatioForPool", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_poolRouteConfig", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "priceRatio" + } + ] + }, + { + "type": "function", + "name": "getUniswapPriceRatioForPoolRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "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" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "priceRatio" + } + ] + }, + { + "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": "0x205aae99a111ce69d7fd9baa2b97a40707f465e0637b055cbb1848f70dc00336", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x7f43c21D4FE1807BF2CF25e6F048A03b57226e03" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/LenderCommitmentGroupBeaconV2.json b/packages/contracts/deployments/bsc/LenderCommitmentGroupBeaconV2.json new file mode 100644 index 000000000..05b5cce7e --- /dev/null +++ b/packages/contracts/deployments/bsc/LenderCommitmentGroupBeaconV2.json @@ -0,0 +1,2017 @@ +{ + "address": "0x645b73AF74D14B488EC296a5C0D00270DDd17Cd6", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + }, + { + "type": "address", + "name": "_uniswapV3Factory" + }, + { + "type": "address", + "name": "_uniswapPricingHelper" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "STANDARD_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_PRICING_HELPER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_V3_FACTORY", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalForCollateralForPoolRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple[]", + "name": "poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "poolIsActivated", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "poolOracleRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMaxPrincipalPerCollateralAmount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_maxPrincipalPerCollateralAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayBypassForAccount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_addr" + }, + { + "type": "bool", + "name": "_bypass" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayBypassForAccount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0xf6E926D7282Ba2Dc1bd580dA36420d2067bEc4A3" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/LenderCommitmentGroupFactory_V2.json b/packages/contracts/deployments/bsc/LenderCommitmentGroupFactory_V2.json new file mode 100644 index 000000000..43a34324d --- /dev/null +++ b/packages/contracts/deployments/bsc/LenderCommitmentGroupFactory_V2.json @@ -0,0 +1,218 @@ +{ + "address": "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x8d2336b8b278516440d04a0c57a3c501bd0a1816e40c5f57d83506d19ba74caa", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x437b82f48Cd7E60742C87f4DF45eCf13B6CA935c" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/LenderManager.json b/packages/contracts/deployments/bsc/LenderManager.json new file mode 100644 index 000000000..e597eec8b --- /dev/null +++ b/packages/contracts/deployments/bsc/LenderManager.json @@ -0,0 +1,441 @@ +{ + "address": "0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_marketRegistry" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "approved", + "indexed": true + }, + { + "type": "uint256", + "name": "tokenId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ApprovalForAll", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "operator", + "indexed": true + }, + { + "type": "bool", + "name": "approved", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "tokenId", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getApproved", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isApprovedForAll", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "operator" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "marketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ownerOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "registerLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_newLender" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "safeTransferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "safeTransferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + }, + { + "type": "bytes", + "name": "data" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setApprovalForAll", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "operator" + }, + { + "type": "bool", + "name": "approved" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "supportsInterface", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "bytes4", + "name": "interfaceId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "tokenURI", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x938c06f23014d88b7ff83441566a4993c653d567371fcb8ce6b35451b2c42bf4", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x7FBCefE4aE4c0C9E70427D0B9F1504Ed39d141BC" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/MarketLiquidityRewards.json b/packages/contracts/deployments/bsc/MarketLiquidityRewards.json new file mode 100644 index 000000000..4c2bc82aa --- /dev/null +++ b/packages/contracts/deployments/bsc/MarketLiquidityRewards.json @@ -0,0 +1,405 @@ +{ + "address": "0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_marketRegistry" + }, + { + "type": "address", + "name": "_collateralManager" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ClaimedRewards", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + }, + { + "type": "address", + "name": "recipient", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CreatedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "address", + "name": "allocator", + "indexed": false + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DecreasedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DeletedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "IncreasedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UpdatedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "allocateRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_allocation", + "components": [ + { + "type": "address", + "name": "allocator" + }, + { + "type": "address", + "name": "rewardTokenAddress" + }, + { + "type": "uint256", + "name": "rewardTokenAmount" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "requiredPrincipalTokenAddress" + }, + { + "type": "address", + "name": "requiredCollateralTokenAddress" + }, + { + "type": "uint256", + "name": "minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "bidStartTimeMin" + }, + { + "type": "uint32", + "name": "bidStartTimeMax" + }, + { + "type": "uint8", + "name": "allocationStrategy" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "allocationId_" + } + ] + }, + { + "type": "function", + "name": "allocatedRewards", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "allocator" + }, + { + "type": "address", + "name": "rewardTokenAddress" + }, + { + "type": "uint256", + "name": "rewardTokenAmount" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "requiredPrincipalTokenAddress" + }, + { + "type": "address", + "name": "requiredCollateralTokenAddress" + }, + { + "type": "uint256", + "name": "minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "bidStartTimeMin" + }, + { + "type": "uint32", + "name": "bidStartTimeMax" + }, + { + "type": "uint8", + "name": "allocationStrategy" + } + ] + }, + { + "type": "function", + "name": "claimRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "deallocateRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_tokenAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getRewardTokenAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllocationAmount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_tokenAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "rewardClaimedForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + }, + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "updateAllocation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "_rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "_bidStartTimeMin" + }, + { + "type": "uint32", + "name": "_bidStartTimeMax" + } + ], + "outputs": [] + } + ], + "transactionHash": "0xb9250e2f1926b689e5dc1b5431d80ff350fad77714b9b55bee47bd8fb15130df", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x5360af9B95701504F783d8654bA02B0AF5155f64" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/MarketRegistry.json b/packages/contracts/deployments/bsc/MarketRegistry.json new file mode 100644 index 000000000..a44934c93 --- /dev/null +++ b/packages/contracts/deployments/bsc/MarketRegistry.json @@ -0,0 +1,1390 @@ +{ + "address": "0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515", + "abi": [ + { + "type": "error", + "name": "NotPayable", + "inputs": [] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerExitMarket", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerRevocation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderExitMarket", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderRevocation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketClosed", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketCreated", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetBidExpirationTime", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketBorrowerAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "bool", + "name": "required", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketFee", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint16", + "name": "feePct", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketFeeRecipient", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "newRecipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketLenderAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "bool", + "name": "required", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketOwner", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "newOwner", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketPaymentType", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint8", + "name": "paymentType", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketURI", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "string", + "name": "uri", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentCycle", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint8", + "name": "paymentCycleType", + "indexed": false + }, + { + "type": "uint32", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentCycleDuration", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentDefaultDuration", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CURRENT_CODE_VERSION", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_MARKET_FEE_PERCENT", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "attestBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + }, + { + "type": "uint8", + "name": "_v" + }, + { + "type": "bytes32", + "name": "_r" + }, + { + "type": "bytes32", + "name": "_s" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + }, + { + "type": "uint8", + "name": "_v" + }, + { + "type": "bytes32", + "name": "_r" + }, + { + "type": "bytes32", + "name": "_s" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "borrowerAttestationSchemaId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowerExitMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "closeMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "createMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_initialOwner" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_requireLenderAttestation" + }, + { + "type": "bool", + "name": "_requireBorrowerAttestation" + }, + { + "type": "uint8", + "name": "_paymentType" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "marketId_" + } + ] + }, + { + "type": "function", + "name": "createMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_initialOwner" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_requireLenderAttestation" + }, + { + "type": "bool", + "name": "_requireBorrowerAttestation" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "marketId_" + } + ] + }, + { + "type": "function", + "name": "getAllVerifiedBorrowersForMarket", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint256", + "name": "_page" + }, + { + "type": "uint256", + "name": "_perPage" + } + ], + "outputs": [ + { + "type": "address[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getAllVerifiedLendersForMarket", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint256", + "name": "_page" + }, + { + "type": "uint256", + "name": "_perPage" + } + ], + "outputs": [ + { + "type": "address[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBidExpirationTime", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketAttestationRequirements", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "lenderAttestationRequired" + }, + { + "type": "bool", + "name": "borrowerAttestationRequired" + } + ] + }, + { + "type": "function", + "name": "getMarketData", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "uint32", + "name": "paymentCycleDuration" + }, + { + "type": "uint32", + "name": "paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "loanExpirationTime" + }, + { + "type": "string", + "name": "metadataURI" + }, + { + "type": "uint16", + "name": "marketplaceFeePercent" + }, + { + "type": "bool", + "name": "lenderAttestationRequired" + } + ] + }, + { + "type": "function", + "name": "getMarketFeeRecipient", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketOwner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketURI", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketplaceFee", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "fee" + } + ] + }, + { + "type": "function", + "name": "getPaymentCycle", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + }, + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPaymentDefaultDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPaymentType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerAS" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isMarketClosed", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isMarketOpen", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isPayable", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isVerifiedBorrower", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + } + ], + "outputs": [ + { + "type": "bool", + "name": "isVerified_" + }, + { + "type": "bytes32", + "name": "uuid_" + } + ] + }, + { + "type": "function", + "name": "isVerifiedLender", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + } + ], + "outputs": [ + { + "type": "bool", + "name": "isVerified_" + }, + { + "type": "bytes32", + "name": "uuid_" + } + ] + }, + { + "type": "function", + "name": "lenderAttestationSchemaId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderExitMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketCount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "resolve", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "address", + "name": "recipient" + }, + { + "type": "bytes", + "name": "schema" + }, + { + "type": "bytes", + "name": "data" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "address", + "name": "attestor" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "revokeBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "revokeLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setBidExpirationTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setBorrowerAttestationRequired", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "bool", + "name": "_required" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setLenderAttestationRequired", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "bool", + "name": "_required" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketFeePercent", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint16", + "name": "_newPercent" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketFeeRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketPaymentType", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint8", + "name": "_newPaymentType" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketURI", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setPaymentCycle", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setPaymentDefaultDuration", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerAS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferMarketOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "updateMarketSettings", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint8", + "name": "_newPaymentType" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_borrowerAttestationRequired" + }, + { + "type": "bool", + "name": "_lenderAttestationRequired" + }, + { + "type": "string", + "name": "_metadataURI" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "version", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "receive", + "stateMutability": "payable" + } + ], + "transactionHash": "0x82a311fab5d5f8ef1c32803b5e6f8ee36fcf3a67c09eda7b78b93963060c2fc4", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/MetaForwarder.json b/packages/contracts/deployments/bsc/MetaForwarder.json new file mode 100644 index 000000000..88c3efee2 --- /dev/null +++ b/packages/contracts/deployments/bsc/MetaForwarder.json @@ -0,0 +1,155 @@ +{ + "address": "0xE11884953B18F8ddC55875CBDAb71b624779D3bB", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "execute", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "tuple", + "name": "req", + "components": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "uint256", + "name": "gas" + }, + { + "type": "uint256", + "name": "nonce" + }, + { + "type": "bytes", + "name": "data" + } + ] + }, + { + "type": "bytes", + "name": "signature" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getNonce", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "verify", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "req", + "components": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "uint256", + "name": "gas" + }, + { + "type": "uint256", + "name": "nonce" + }, + { + "type": "bytes", + "name": "data" + } + ] + }, + { + "type": "bytes", + "name": "signature" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + } + ], + "transactionHash": "0xa9e9223f9263ca47dfc7594bb8d0441a09d73407cdc995a3537acead67764072", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0xe7768f28455eE81D7B415f4F5019A316c27AB445" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/ProtocolPausingManager.json b/packages/contracts/deployments/bsc/ProtocolPausingManager.json new file mode 100644 index 000000000..1728a22e8 --- /dev/null +++ b/packages/contracts/deployments/bsc/ProtocolPausingManager.json @@ -0,0 +1,310 @@ +{ + "address": "0x357fa5700f67a3DA1EC49ea19F872B3a35fE043D", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidations", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedProtocol", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PauserAdded", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PauserRemoved", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidations", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedProtocol", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "addPauser", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_pauser" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getLastPausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isPauser", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidationsPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseLiquidations", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseProtocol", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauserRoleBearer", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "protocolPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "removePauser", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_pauser" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidations", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseProtocol", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + } + ], + "transactionHash": "0xe47a5df72d3bda7d7d67e6e8d37d37d78f917c1dd3abeee12553206ab5a4ae47", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x13a5735F356B4ede9D3F65D3eDdb62651df1cC37" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/ReputationManager.json b/packages/contracts/deployments/bsc/ReputationManager.json new file mode 100644 index 000000000..33d0831ef --- /dev/null +++ b/packages/contracts/deployments/bsc/ReputationManager.json @@ -0,0 +1,218 @@ +{ + "address": "0xfCd6Aa92D399260E8309800316CEc9b1F123621e", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarkAdded", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + }, + { + "type": "uint8", + "name": "repMark", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarkRemoved", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + }, + { + "type": "uint8", + "name": "repMark", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CONTROLLER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCurrentDefaultLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCurrentDelinquentLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getDefaultedLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getDelinquentLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "updateAccountReputation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "updateAccountReputation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + }, + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + } + ], + "transactionHash": "0x52cca139a342510c50ba8fc203f46dd066b1b266fa9692e9d1231e81516b8bb4", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0xa1106d888F1FA689c6935e0983687432eF2a28c1" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/SmartCommitmentForwarder.json b/packages/contracts/deployments/bsc/SmartCommitmentForwarder.json new file mode 100644 index 000000000..83be973b1 --- /dev/null +++ b/packages/contracts/deployments/bsc/SmartCommitmentForwarder.json @@ -0,0 +1,578 @@ +{ + "address": "0xb7695470E9c8d6E84F4786C240960B7822106b63", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_protocolAddress" + }, + { + "type": "address", + "name": "_marketRegistry" + } + ] + }, + { + "type": "error", + "name": "InsufficientBorrowerCollateral", + "inputs": [ + { + "type": "uint256", + "name": "required" + }, + { + "type": "uint256", + "name": "actual" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ExercisedSmartCommitment", + "inputs": [ + { + "type": "address", + "name": "smartCommitmentAddress", + "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": "OracleAddressChanged", + "inputs": [ + { + "type": "address", + "name": "previousOracle", + "indexed": true + }, + { + "type": "address", + "name": "newOracle", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "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": "acceptSmartCommitmentWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_smartCommitmentAddress" + }, + { + "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": "addExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLiquidationProtocolFeePercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "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": "hasExtension", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + }, + { + "type": "address", + "name": "extension" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "hypernativeOracleIsStrictMode", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isOracleApproved", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isOracleApprovedAllowEOA", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isOracleApprovedOnlyAllowEOA", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidationProtocolFeePercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "oracleRegister", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pause", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "revokeExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setIsStrictMode", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "bool", + "name": "_mode" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setLiquidationProtocolFeePercent", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_percent" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setOracle", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_oracle" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpause", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + } + ], + "transactionHash": "0x1f9c3cfd8e697e3675cb91a56ad82b12f6e7d1db4be9984fc709995e3fa5b851", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x48EE9c344d5C6d202F4b3225A694957a3412008d" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/SwapRolloverLoan.json b/packages/contracts/deployments/bsc/SwapRolloverLoan.json new file mode 100644 index 000000000..e7f9f40a7 --- /dev/null +++ b/packages/contracts/deployments/bsc/SwapRolloverLoan.json @@ -0,0 +1,514 @@ +{ + "address": "0x7292385522F11390B2A7dd4677528fFce03b80db", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_factory" + }, + { + "type": "address", + "name": "_WETH9" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "RolloverLoanComplete", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": false + }, + { + "type": "uint256", + "name": "originalLoanId", + "indexed": false + }, + { + "type": "uint256", + "name": "newLoanId", + "indexed": false + }, + { + "type": "uint256", + "name": "fundsRemaining", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "RolloverWithReferral", + "inputs": [ + { + "type": "uint256", + "name": "newLoanId", + "indexed": false + }, + { + "type": "address", + "name": "flashToken", + "indexed": false + }, + { + "type": "address", + "name": "rewardRecipient", + "indexed": false + }, + { + "type": "uint256", + "name": "rewardAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "atmId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "WETH9", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateRolloverAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "marketFeePct" + }, + { + "type": "uint16", + "name": "protocolFeePct" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "_rewardAmount" + }, + { + "type": "uint16", + "name": "_flashloanFeePct" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "_flashAmount" + }, + { + "type": "int256", + "name": "_borrowerAmount" + } + ] + }, + { + "type": "function", + "name": "factory", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketFeePct", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketIdForCommitment", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getUniswapPoolAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "refundETH", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "rolloverLoanWithFlashSwap", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "_borrowerAmount" + }, + { + "type": "tuple", + "name": "_flashSwapArgs", + "components": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + }, + { + "type": "uint256", + "name": "flashAmount" + }, + { + "type": "bool", + "name": "borrowToken1" + } + ] + }, + { + "type": "tuple", + "name": "_acceptCommitmentArgs", + "components": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "address", + "name": "smartCommitmentAddress" + }, + { + "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": "function", + "name": "rolloverLoanWithFlashSwapRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "_borrowerAmount" + }, + { + "type": "uint256", + "name": "_rewardAmount" + }, + { + "type": "address", + "name": "_rewardRecipient" + }, + { + "type": "uint256", + "name": "_atmId" + }, + { + "type": "tuple", + "name": "_flashSwapArgs", + "components": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + }, + { + "type": "uint256", + "name": "flashAmount" + }, + { + "type": "bool", + "name": "borrowToken1" + } + ] + }, + { + "type": "tuple", + "name": "_acceptCommitmentArgs", + "components": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "address", + "name": "smartCommitmentAddress" + }, + { + "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": "function", + "name": "sweepToken", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amountMinimum" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "uniswapV3FlashCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "fee0" + }, + { + "type": "uint256", + "name": "fee1" + }, + { + "type": "bytes", + "name": "data" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unwrapWETH9", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "uint256", + "name": "amountMinimum" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + }, + { + "type": "receive", + "stateMutability": "payable" + } + ], + "transactionHash": "0x8bc368aa14a89ce357de79e93b358a1942e1a5006d291564b11390df24dfc18a", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0x203ee2F172826Fa46A175230DF260188fE0C96Fc" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/TellerAS.json b/packages/contracts/deployments/bsc/TellerAS.json new file mode 100644 index 000000000..585cdb3ce --- /dev/null +++ b/packages/contracts/deployments/bsc/TellerAS.json @@ -0,0 +1,1089 @@ +{ + "address": "0x0708480670BdE591e275B06Cd19EcaDFC93A1f16", + "abi": [ + { + "inputs": [ + { + "internalType": "contract IASRegistry", + "name": "registry", + "type": "address" + }, + { + "internalType": "contract IEASEIP712Verifier", + "name": "verifier", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "AccessDenied", + "type": "error" + }, + { + "inputs": [], + "name": "AlreadyRevoked", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidAttestation", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidExpirationTime", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidOffset", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidRegistry", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidSchema", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidVerifier", + "type": "error" + }, + { + "inputs": [], + "name": "NotFound", + "type": "error" + }, + { + "inputs": [], + "name": "NotPayable", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "Attested", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "Revoked", + "type": "event" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "attest", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "attestByDelegation", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [], + "name": "getASRegistry", + "outputs": [ + { + "internalType": "contract IASRegistry", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getAttestation", + "outputs": [ + { + "components": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint256", + "name": "time", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "revocationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "internalType": "struct IEAS.Attestation", + "name": "", + "type": "tuple" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getAttestationsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getEIP712Verifier", + "outputs": [ + { + "internalType": "contract IEASEIP712Verifier", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getLastUUID", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getReceivedAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getReceivedAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getRelatedAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getRelatedAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getSchemaAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getSchemaAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getSentAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getSentAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "isAttestationActive", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "isAttestationValid", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "revoke", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "revokeByDelegation", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x4dddeeed3d82377af8b5589c868858ba9a9459b364b6fef6ec846480dfccef5c", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x0708480670BdE591e275B06Cd19EcaDFC93A1f16", + "transactionIndex": 42, + "gasUsed": "1476401", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xa96286b981d21744bd953a9b3574de798f94eb97572c54a1d1edb571bc873749", + "transactionHash": "0x4dddeeed3d82377af8b5589c868858ba9a9459b364b6fef6ec846480dfccef5c", + "logs": [], + "blockNumber": 81086289, + "cumulativeGasUsed": "8445116", + "status": 1, + "byzantium": true + }, + "args": [ + "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", + "0x0D1047229B9851eACE463Fb25f27982a5127c20F" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"contract IASRegistry\",\"name\":\"registry\",\"type\":\"address\"},{\"internalType\":\"contract IEASEIP712Verifier\",\"name\":\"verifier\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyRevoked\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAttestation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidExpirationTime\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidOffset\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidRegistry\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSchema\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidVerifier\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotFound\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotPayable\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"Attested\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"Revoked\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"attest\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"attestByDelegation\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getASRegistry\",\"outputs\":[{\"internalType\":\"contract IASRegistry\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getAttestation\",\"outputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"time\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"revocationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"internalType\":\"struct IEAS.Attestation\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getAttestationsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getEIP712Verifier\",\"outputs\":[{\"internalType\":\"contract IEASEIP712Verifier\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getLastUUID\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getReceivedAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getReceivedAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getRelatedAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getRelatedAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getSchemaAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getSchemaAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getSentAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getSentAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"isAttestationActive\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"isAttestationValid\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"revoke\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"revokeByDelegation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"attest(address,bytes32,uint256,bytes32,bytes)\":{\"details\":\"Attests to a specific AS.\",\"params\":{\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The UUID of the new attestation.\"}},\"attestByDelegation(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)\":{\"details\":\"Attests to a specific AS using a provided EIP712 signature.\",\"params\":{\"attester\":\"The attesting account.\",\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"r\":\"The x-coordinate of the nonce R.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"s\":\"The signature data.\",\"schema\":\"The UUID of the AS.\",\"v\":\"The recovery ID.\"},\"returns\":{\"_0\":\"The UUID of the new attestation.\"}},\"constructor\":{\"details\":\"Creates a new EAS instance.\",\"params\":{\"registry\":\"The address of the global AS registry.\",\"verifier\":\"The address of the EIP712 verifier.\"}},\"getASRegistry()\":{\"details\":\"Returns the address of the AS global registry.\",\"returns\":{\"_0\":\"The address of the AS global registry.\"}},\"getAttestation(bytes32)\":{\"details\":\"Returns an existing attestation by UUID.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"The attestation data members.\"}},\"getAttestationsCount()\":{\"details\":\"Returns the global counter for the total number of attestations.\",\"returns\":{\"_0\":\"The global counter for the total number of attestations.\"}},\"getEIP712Verifier()\":{\"details\":\"Returns the address of the EIP712 verifier used to verify signed attestations.\",\"returns\":{\"_0\":\"The address of the EIP712 verifier used to verify signed attestations.\"}},\"getReceivedAttestationUUIDs(address,bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all received attestation UUIDs.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"recipient\":\"The recipient of the attestation.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getReceivedAttestationUUIDsCount(address,bytes32)\":{\"details\":\"Returns the number of received attestation UUIDs.\",\"params\":{\"recipient\":\"The recipient of the attestation.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"getRelatedAttestationUUIDs(bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all attestations related to a specific attestation.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"start\":\"The offset to start from.\",\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getRelatedAttestationUUIDsCount(bytes32)\":{\"details\":\"Returns the number of related attestation UUIDs.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"The number of related attestations.\"}},\"getSchemaAttestationUUIDs(bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all per-schema attestation UUIDs.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getSchemaAttestationUUIDsCount(bytes32)\":{\"details\":\"Returns the number of per-schema attestation UUIDs.\",\"params\":{\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"getSentAttestationUUIDs(address,bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all sent attestation UUIDs.\",\"params\":{\"attester\":\"The attesting account.\",\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getSentAttestationUUIDsCount(address,bytes32)\":{\"details\":\"Returns the number of sent attestation UUIDs.\",\"params\":{\"recipient\":\"The recipient of the attestation.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"isAttestationActive(bytes32)\":{\"details\":\"Checks whether an attestation is active.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"Whether an attestation is active.\"}},\"isAttestationValid(bytes32)\":{\"details\":\"Checks whether an attestation exists.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"Whether an attestation exists.\"}},\"revoke(bytes32)\":{\"details\":\"Revokes an existing attestation to a specific AS.\",\"params\":{\"uuid\":\"The UUID of the attestation to revoke.\"}},\"revokeByDelegation(bytes32,address,uint8,bytes32,bytes32)\":{\"details\":\"Attests to a specific AS using a provided EIP712 signature.\",\"params\":{\"attester\":\"The attesting account.\",\"r\":\"The x-coordinate of the nonce R.\",\"s\":\"The signature data.\",\"uuid\":\"The UUID of the attestation to revoke.\",\"v\":\"The recovery ID.\"}}},\"title\":\"TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerAS.sol\":\"TellerAS\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60c06040523480156200001157600080fd5b5060405162001ade38038062001ade8339810160408190526200003491620000b5565b6001600160a01b0382166200005c576040516311a1e69760e01b815260040160405180910390fd5b6001600160a01b038116620000845760405163baa3de5f60e01b815260040160405180910390fd5b6001600160a01b039182166080521660a052620000f4565b6001600160a01b0381168114620000b257600080fd5b50565b60008060408385031215620000c957600080fd5b8251620000d6816200009c565b6020840151909250620000e9816200009c565b809150509250929050565b60805160a0516119af6200012f600039600081816101b301528181610692015261092501526000818161028701526109cd01526119af6000f3fe60806040526004361061011f5760003560e01c8063a3112a64116100a0578063d8c5ebd411610064578063d8c5ebd4146103a0578063e30bb563146103e3578063ef0a309814610412578063f96e501314610427578063ffa1ad741461043c57600080fd5b8063a3112a64146102be578063b75c7dc6146102eb578063c042d88f1461030d578063c334947c14610350578063d87647b21461038057600080fd5b806362196643116100e7578063621966431461020b57806363583538146102385780637f04f2841461025857806381fa6cd314610278578063930ed013146102ab57600080fd5b80630560f90f1461012457806309a954cd14610164578063105152981461017757806315cd31a1146101a45780631bc9a07a146101eb575b600080fd5b34801561013057600080fd5b5061015161013f3660046111e8565b60009081526020819052604090205490565b6040519081526020015b60405180910390f35b61015161017236600461125f565b610478565b34801561018357600080fd5b506101976101923660046112e0565b610494565b60405161015b9190611336565b3480156101b057600080fd5b507f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161015b565b3480156101f757600080fd5b506101976102063660046112e0565b61051a565b34801561021757600080fd5b506101516102263660046111e8565b60009081526003602052604090205490565b34801561024457600080fd5b5061019761025336600461137a565b610594565b34801561026457600080fd5b5061019761027336600461137a565b61060c565b34801561028457600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006101d3565b6101516102b93660046113d1565b610678565b3480156102ca57600080fd5b506102de6102d93660046111e8565b610729565b60405161015b91906114d7565b3480156102f757600080fd5b5061030b6103063660046111e8565b61088c565b005b34801561031957600080fd5b50610151610328366004611567565b6001600160a01b03919091166000908152600260209081526040808320938352929052205490565b34801561035c57600080fd5b5061037061036b3660046111e8565b610899565b604051901515815260200161015b565b34801561038c57600080fd5b5061030b61039b366004611593565b6108e8565b3480156103ac57600080fd5b506101516103bb366004611567565b6001600160a01b03919091166000908152600160209081526040808320938352929052205490565b3480156103ef57600080fd5b506103706103fe3660046111e8565b600090815260046020526040902054151590565b34801561041e57600080fd5b50600654610151565b34801561043357600080fd5b50600554610151565b34801561044857600080fd5b5061046b604051806040016040528060038152602001620605c760eb1b81525081565b60405161015b91906115e3565b600061048987878787878733610992565b979650505050505050565b6001600160a01b03851660009081526001602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020905b8154815260200190600101908083116104ef575b5050505050858585610ede565b9695505050505050565b6001600160a01b03851660009081526002602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b60606106016003600087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b90505b949350505050565b606061060160008087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b604051636aeb49a560e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636aeb49a5906106d9908e908e908e908e908e908e908e908e908e908e90600401611626565b600060405180830381600087803b1580156106f357600080fd5b505af1158015610707573d6000803e3d6000fd5b5050505061071a8b8b8b8b8b8b8b610992565b9b9a5050505050505050505050565b604080516101208101825260008082526020820181905291810182905260608082018390526080820183905260a0820183905260c0820183905260e08201929092526101008101919091526000828152600460208181526040928390208351610120810185528154815260018201549281019290925260028101546001600160a01b039081169483019490945260038101549093166060820152908201546080820152600582015460a0820152600682015460c0820152600782015460e08201526008820180549192916101008401919061080390611689565b80601f016020809104026020016040519081016040528092919081815260200182805461082f90611689565b801561087c5780601f106108515761010080835404028352916020019161087c565b820191906000526020600020905b81548152906001019060200180831161085f57829003601f168201915b5050505050815250509050919050565b6108968133611013565b50565b600081815260046020526040812054151580156108c757506000828152600460205260409020600501544211155b80156108e25750600082815260046020526040902060060154155b92915050565b604051631863f01d60e01b8152600481018690526001600160a01b03858116602483015260ff8516604483015260648201849052608482018390527f00000000000000000000000000000000000000000000000000000000000000001690631863f01d9060a401600060405180830381600087803b15801561096957600080fd5b505af115801561097d573d6000803e3d6000fd5b5050505061098b8585611013565b5050505050565b60004286116109b4576040516308e8b93760e01b815260040160405180910390fd5b6040516339243ea960e11b8152600481018890526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906372487d5290602401600060405180830381865afa158015610a1c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610a449190810190611734565b8051909150610a6657604051635f9bd90760e11b815260040160405180910390fd5b60208101516001600160a01b03811615610ba1573415801590610ae85750806001600160a01b031663ce46e0466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ac2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ae6919061181c565b155b15610b0657604051631574f9f360e01b815260040160405180910390fd5b806001600160a01b031663947a75b4348c85606001518a8a8e8b6040518863ffffffff1660e01b8152600401610b4196959493929190611839565b60206040518083038185885af1158015610b5f573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610b84919061181c565b610ba15760405163bd8ba84d60e01b815260040160405180910390fd5b60006040518061012001604052806000801b81526020018b81526020018c6001600160a01b03168152602001866001600160a01b031681526020014281526020018a81526020016000815260200189815260200188888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050509152509050610c38816110e9565b600681905550600654816000018181525050600160008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505560026000866001600160a01b03166001600160a01b0316815260200190815260200160002060008b81526020019081526020016000206006549080600181540180825580915050600190039060005260206000200160009091909190915055600360008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505580600460006006548152602001908152602001600020600082015181600001556020820151816001015560408201518160020160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a0820151816005015560c0820151816006015560e08201518160070155610100820151816008019080519060200190610e0d92919061114f565b50506005805491506000610e20836118a0565b90915550508715610e7c57600088815260046020526040902054610e575760405163c5723b5160e01b815260040160405180910390fd5b6000888152602081815260408220600654815460018101835591845291909220909101555b89856001600160a01b03168c6001600160a01b03167f8bf46bf4cfd674fa735a3d63ec1c9ad4153f033c290341f3a588b75685141b35600654604051610ec491815260200190565b60405180910390a450506006549998505050505050505050565b835160609080610efe575050604080516000815260208101909152610604565b808510610f1d5760405162ed0ab960e11b815260040160405180910390fd5b83610f2881876118bb565b821015610f3c57610f3986836118d3565b90505b60008167ffffffffffffffff811115610f5757610f576116c4565b604051908082528060200260200182016040528015610f80578160200160208202803683370190505b50905060005b82811015611007578886610fa357610f9e828a6118bb565b610fc2565b610fad828a6118bb565b610fb89060016118bb565b610fc290866118d3565b81518110610fd257610fd26118ea565b6020026020010151828281518110610fec57610fec6118ea565b6020908102919091010152611000816118a0565b9050610f86565b50979650505050505050565b600082815260046020526040902080546110405760405163c5723b5160e01b815260040160405180910390fd5b60038101546001600160a01b0383811691161461107057604051634ca8886760e01b815260040160405180910390fd5b6006810154156110935760405163905e710760e01b815260040160405180910390fd5b426006820155600181015460028201546040518581526001600160a01b038581169216907ff930a6e2523c9cc298691873087a740550b8fc85a0680830414c148ed927f6159060200160405180910390a4505050565b6020808201516040808401516060850151608086015160a08701516101008801518551808701875260018152600160fe1b818a0152600554965160009961113299989101611900565b604051602081830303815290604052805190602001209050919050565b82805461115b90611689565b90600052602060002090601f01602090048101928261117d57600085556111c3565b82601f1061119657805160ff19168380011785556111c3565b828001600101855582156111c3579182015b828111156111c35782518255916020019190600101906111a8565b506111cf9291506111d3565b5090565b5b808211156111cf57600081556001016111d4565b6000602082840312156111fa57600080fd5b5035919050565b6001600160a01b038116811461089657600080fd5b60008083601f84011261122857600080fd5b50813567ffffffffffffffff81111561124057600080fd5b60208301915083602082850101111561125857600080fd5b9250929050565b60008060008060008060a0878903121561127857600080fd5b863561128381611201565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff8111156112b457600080fd5b6112c089828a01611216565b979a9699509497509295939492505050565b801515811461089657600080fd5b600080600080600060a086880312156112f857600080fd5b853561130381611201565b94506020860135935060408601359250606086013591506080860135611328816112d2565b809150509295509295909350565b6020808252825182820181905260009190848201906040850190845b8181101561136e57835183529284019291840191600101611352565b50909695505050505050565b6000806000806080858703121561139057600080fd5b84359350602085013592506040850135915060608501356113b0816112d2565b939692955090935050565b803560ff811681146113cc57600080fd5b919050565b6000806000806000806000806000806101208b8d0312156113f157600080fd5b8a356113fc81611201565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff81111561142d57600080fd5b6114398d828e01611216565b90975095505060a08b013561144d81611201565b935061145b60c08c016113bb565b925060e08b013591506101008b013590509295989b9194979a5092959850565b60005b8381101561149657818101518382015260200161147e565b838111156114a5576000848401525b50505050565b600081518084526114c381602086016020860161147b565b601f01601f19169290920160200192915050565b6020815281516020820152602082015160408201526000604083015161150860608401826001600160a01b03169052565b5060608301516001600160a01b038116608084015250608083015160a083015260a083015160c083015260c083015160e083015260e08301516101008181850152808501519150506101208081850152506106046101408401826114ab565b6000806040838503121561157a57600080fd5b823561158581611201565b946020939093013593505050565b600080600080600060a086880312156115ab57600080fd5b8535945060208601356115bd81611201565b93506115cb604087016113bb565b94979396509394606081013594506080013592915050565b6020815260006115f660208301846114ab565b9392505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b600061012060018060a01b03808e1684528c60208501528b60408501528a606085015281608085015261165c8285018a8c6115fd565b971660a0840152505060ff9390931660c084015260e0830191909152610100909101529695505050505050565b600181811c9082168061169d57607f821691505b602082108114156116be57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff811182821017156116fd576116fd6116c4565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561172c5761172c6116c4565b604052919050565b6000602080838503121561174757600080fd5b825167ffffffffffffffff8082111561175f57600080fd5b908401906080828703121561177357600080fd5b61177b6116da565b825181528383015161178c81611201565b81850152604083810151908201526060830151828111156117ac57600080fd5b80840193505086601f8401126117c157600080fd5b8251828111156117d3576117d36116c4565b6117e5601f8201601f19168601611703565b925080835287858286010111156117fb57600080fd5b61180a8186850187870161147b565b50606081019190915295945050505050565b60006020828403121561182e57600080fd5b81516115f6816112d2565b600060018060a01b03808916835260a0602084015261185b60a08401896114ab565b838103604085015261186e81888a6115fd565b6060850196909652509290921660809091015250949350505050565b634e487b7160e01b600052601160045260246000fd5b60006000198214156118b4576118b461188a565b5060010190565b600082198211156118ce576118ce61188a565b500190565b6000828210156118e5576118e561188a565b500390565b634e487b7160e01b600052603260045260246000fd5b88815260006bffffffffffffffffffffffff19808a60601b166020840152808960601b16603484015250866048830152856068830152845161194981608885016020890161147b565b84519083019061196081608884016020890161147b565b016088810193909352505060a80197965050505050505056fea26469706673582212206b83e2d5fb2a34e86903468d36eb72ed8828b1852d24733e2c4f36d7f72717d664736f6c634300080b0033", + "deployedBytecode": "0x60806040526004361061011f5760003560e01c8063a3112a64116100a0578063d8c5ebd411610064578063d8c5ebd4146103a0578063e30bb563146103e3578063ef0a309814610412578063f96e501314610427578063ffa1ad741461043c57600080fd5b8063a3112a64146102be578063b75c7dc6146102eb578063c042d88f1461030d578063c334947c14610350578063d87647b21461038057600080fd5b806362196643116100e7578063621966431461020b57806363583538146102385780637f04f2841461025857806381fa6cd314610278578063930ed013146102ab57600080fd5b80630560f90f1461012457806309a954cd14610164578063105152981461017757806315cd31a1146101a45780631bc9a07a146101eb575b600080fd5b34801561013057600080fd5b5061015161013f3660046111e8565b60009081526020819052604090205490565b6040519081526020015b60405180910390f35b61015161017236600461125f565b610478565b34801561018357600080fd5b506101976101923660046112e0565b610494565b60405161015b9190611336565b3480156101b057600080fd5b507f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161015b565b3480156101f757600080fd5b506101976102063660046112e0565b61051a565b34801561021757600080fd5b506101516102263660046111e8565b60009081526003602052604090205490565b34801561024457600080fd5b5061019761025336600461137a565b610594565b34801561026457600080fd5b5061019761027336600461137a565b61060c565b34801561028457600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006101d3565b6101516102b93660046113d1565b610678565b3480156102ca57600080fd5b506102de6102d93660046111e8565b610729565b60405161015b91906114d7565b3480156102f757600080fd5b5061030b6103063660046111e8565b61088c565b005b34801561031957600080fd5b50610151610328366004611567565b6001600160a01b03919091166000908152600260209081526040808320938352929052205490565b34801561035c57600080fd5b5061037061036b3660046111e8565b610899565b604051901515815260200161015b565b34801561038c57600080fd5b5061030b61039b366004611593565b6108e8565b3480156103ac57600080fd5b506101516103bb366004611567565b6001600160a01b03919091166000908152600160209081526040808320938352929052205490565b3480156103ef57600080fd5b506103706103fe3660046111e8565b600090815260046020526040902054151590565b34801561041e57600080fd5b50600654610151565b34801561043357600080fd5b50600554610151565b34801561044857600080fd5b5061046b604051806040016040528060038152602001620605c760eb1b81525081565b60405161015b91906115e3565b600061048987878787878733610992565b979650505050505050565b6001600160a01b03851660009081526001602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020905b8154815260200190600101908083116104ef575b5050505050858585610ede565b9695505050505050565b6001600160a01b03851660009081526002602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b60606106016003600087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b90505b949350505050565b606061060160008087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b604051636aeb49a560e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636aeb49a5906106d9908e908e908e908e908e908e908e908e908e908e90600401611626565b600060405180830381600087803b1580156106f357600080fd5b505af1158015610707573d6000803e3d6000fd5b5050505061071a8b8b8b8b8b8b8b610992565b9b9a5050505050505050505050565b604080516101208101825260008082526020820181905291810182905260608082018390526080820183905260a0820183905260c0820183905260e08201929092526101008101919091526000828152600460208181526040928390208351610120810185528154815260018201549281019290925260028101546001600160a01b039081169483019490945260038101549093166060820152908201546080820152600582015460a0820152600682015460c0820152600782015460e08201526008820180549192916101008401919061080390611689565b80601f016020809104026020016040519081016040528092919081815260200182805461082f90611689565b801561087c5780601f106108515761010080835404028352916020019161087c565b820191906000526020600020905b81548152906001019060200180831161085f57829003601f168201915b5050505050815250509050919050565b6108968133611013565b50565b600081815260046020526040812054151580156108c757506000828152600460205260409020600501544211155b80156108e25750600082815260046020526040902060060154155b92915050565b604051631863f01d60e01b8152600481018690526001600160a01b03858116602483015260ff8516604483015260648201849052608482018390527f00000000000000000000000000000000000000000000000000000000000000001690631863f01d9060a401600060405180830381600087803b15801561096957600080fd5b505af115801561097d573d6000803e3d6000fd5b5050505061098b8585611013565b5050505050565b60004286116109b4576040516308e8b93760e01b815260040160405180910390fd5b6040516339243ea960e11b8152600481018890526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906372487d5290602401600060405180830381865afa158015610a1c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610a449190810190611734565b8051909150610a6657604051635f9bd90760e11b815260040160405180910390fd5b60208101516001600160a01b03811615610ba1573415801590610ae85750806001600160a01b031663ce46e0466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ac2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ae6919061181c565b155b15610b0657604051631574f9f360e01b815260040160405180910390fd5b806001600160a01b031663947a75b4348c85606001518a8a8e8b6040518863ffffffff1660e01b8152600401610b4196959493929190611839565b60206040518083038185885af1158015610b5f573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610b84919061181c565b610ba15760405163bd8ba84d60e01b815260040160405180910390fd5b60006040518061012001604052806000801b81526020018b81526020018c6001600160a01b03168152602001866001600160a01b031681526020014281526020018a81526020016000815260200189815260200188888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050509152509050610c38816110e9565b600681905550600654816000018181525050600160008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505560026000866001600160a01b03166001600160a01b0316815260200190815260200160002060008b81526020019081526020016000206006549080600181540180825580915050600190039060005260206000200160009091909190915055600360008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505580600460006006548152602001908152602001600020600082015181600001556020820151816001015560408201518160020160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a0820151816005015560c0820151816006015560e08201518160070155610100820151816008019080519060200190610e0d92919061114f565b50506005805491506000610e20836118a0565b90915550508715610e7c57600088815260046020526040902054610e575760405163c5723b5160e01b815260040160405180910390fd5b6000888152602081815260408220600654815460018101835591845291909220909101555b89856001600160a01b03168c6001600160a01b03167f8bf46bf4cfd674fa735a3d63ec1c9ad4153f033c290341f3a588b75685141b35600654604051610ec491815260200190565b60405180910390a450506006549998505050505050505050565b835160609080610efe575050604080516000815260208101909152610604565b808510610f1d5760405162ed0ab960e11b815260040160405180910390fd5b83610f2881876118bb565b821015610f3c57610f3986836118d3565b90505b60008167ffffffffffffffff811115610f5757610f576116c4565b604051908082528060200260200182016040528015610f80578160200160208202803683370190505b50905060005b82811015611007578886610fa357610f9e828a6118bb565b610fc2565b610fad828a6118bb565b610fb89060016118bb565b610fc290866118d3565b81518110610fd257610fd26118ea565b6020026020010151828281518110610fec57610fec6118ea565b6020908102919091010152611000816118a0565b9050610f86565b50979650505050505050565b600082815260046020526040902080546110405760405163c5723b5160e01b815260040160405180910390fd5b60038101546001600160a01b0383811691161461107057604051634ca8886760e01b815260040160405180910390fd5b6006810154156110935760405163905e710760e01b815260040160405180910390fd5b426006820155600181015460028201546040518581526001600160a01b038581169216907ff930a6e2523c9cc298691873087a740550b8fc85a0680830414c148ed927f6159060200160405180910390a4505050565b6020808201516040808401516060850151608086015160a08701516101008801518551808701875260018152600160fe1b818a0152600554965160009961113299989101611900565b604051602081830303815290604052805190602001209050919050565b82805461115b90611689565b90600052602060002090601f01602090048101928261117d57600085556111c3565b82601f1061119657805160ff19168380011785556111c3565b828001600101855582156111c3579182015b828111156111c35782518255916020019190600101906111a8565b506111cf9291506111d3565b5090565b5b808211156111cf57600081556001016111d4565b6000602082840312156111fa57600080fd5b5035919050565b6001600160a01b038116811461089657600080fd5b60008083601f84011261122857600080fd5b50813567ffffffffffffffff81111561124057600080fd5b60208301915083602082850101111561125857600080fd5b9250929050565b60008060008060008060a0878903121561127857600080fd5b863561128381611201565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff8111156112b457600080fd5b6112c089828a01611216565b979a9699509497509295939492505050565b801515811461089657600080fd5b600080600080600060a086880312156112f857600080fd5b853561130381611201565b94506020860135935060408601359250606086013591506080860135611328816112d2565b809150509295509295909350565b6020808252825182820181905260009190848201906040850190845b8181101561136e57835183529284019291840191600101611352565b50909695505050505050565b6000806000806080858703121561139057600080fd5b84359350602085013592506040850135915060608501356113b0816112d2565b939692955090935050565b803560ff811681146113cc57600080fd5b919050565b6000806000806000806000806000806101208b8d0312156113f157600080fd5b8a356113fc81611201565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff81111561142d57600080fd5b6114398d828e01611216565b90975095505060a08b013561144d81611201565b935061145b60c08c016113bb565b925060e08b013591506101008b013590509295989b9194979a5092959850565b60005b8381101561149657818101518382015260200161147e565b838111156114a5576000848401525b50505050565b600081518084526114c381602086016020860161147b565b601f01601f19169290920160200192915050565b6020815281516020820152602082015160408201526000604083015161150860608401826001600160a01b03169052565b5060608301516001600160a01b038116608084015250608083015160a083015260a083015160c083015260c083015160e083015260e08301516101008181850152808501519150506101208081850152506106046101408401826114ab565b6000806040838503121561157a57600080fd5b823561158581611201565b946020939093013593505050565b600080600080600060a086880312156115ab57600080fd5b8535945060208601356115bd81611201565b93506115cb604087016113bb565b94979396509394606081013594506080013592915050565b6020815260006115f660208301846114ab565b9392505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b600061012060018060a01b03808e1684528c60208501528b60408501528a606085015281608085015261165c8285018a8c6115fd565b971660a0840152505060ff9390931660c084015260e0830191909152610100909101529695505050505050565b600181811c9082168061169d57607f821691505b602082108114156116be57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff811182821017156116fd576116fd6116c4565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561172c5761172c6116c4565b604052919050565b6000602080838503121561174757600080fd5b825167ffffffffffffffff8082111561175f57600080fd5b908401906080828703121561177357600080fd5b61177b6116da565b825181528383015161178c81611201565b81850152604083810151908201526060830151828111156117ac57600080fd5b80840193505086601f8401126117c157600080fd5b8251828111156117d3576117d36116c4565b6117e5601f8201601f19168601611703565b925080835287858286010111156117fb57600080fd5b61180a8186850187870161147b565b50606081019190915295945050505050565b60006020828403121561182e57600080fd5b81516115f6816112d2565b600060018060a01b03808916835260a0602084015261185b60a08401896114ab565b838103604085015261186e81888a6115fd565b6060850196909652509290921660809091015250949350505050565b634e487b7160e01b600052601160045260246000fd5b60006000198214156118b4576118b461188a565b5060010190565b600082198211156118ce576118ce61188a565b500190565b6000828210156118e5576118e561188a565b500390565b634e487b7160e01b600052603260045260246000fd5b88815260006bffffffffffffffffffffffff19808a60601b166020840152808960601b16603484015250866048830152856068830152845161194981608885016020890161147b565b84519083019061196081608884016020890161147b565b016088810193909352505060a80197965050505050505056fea26469706673582212206b83e2d5fb2a34e86903468d36eb72ed8828b1852d24733e2c4f36d7f72717d664736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "attest(address,bytes32,uint256,bytes32,bytes)": { + "details": "Attests to a specific AS.", + "params": { + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The UUID of the new attestation." + } + }, + "attestByDelegation(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)": { + "details": "Attests to a specific AS using a provided EIP712 signature.", + "params": { + "attester": "The attesting account.", + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "r": "The x-coordinate of the nonce R.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "s": "The signature data.", + "schema": "The UUID of the AS.", + "v": "The recovery ID." + }, + "returns": { + "_0": "The UUID of the new attestation." + } + }, + "constructor": { + "details": "Creates a new EAS instance.", + "params": { + "registry": "The address of the global AS registry.", + "verifier": "The address of the EIP712 verifier." + } + }, + "getASRegistry()": { + "details": "Returns the address of the AS global registry.", + "returns": { + "_0": "The address of the AS global registry." + } + }, + "getAttestation(bytes32)": { + "details": "Returns an existing attestation by UUID.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "The attestation data members." + } + }, + "getAttestationsCount()": { + "details": "Returns the global counter for the total number of attestations.", + "returns": { + "_0": "The global counter for the total number of attestations." + } + }, + "getEIP712Verifier()": { + "details": "Returns the address of the EIP712 verifier used to verify signed attestations.", + "returns": { + "_0": "The address of the EIP712 verifier used to verify signed attestations." + } + }, + "getReceivedAttestationUUIDs(address,bytes32,uint256,uint256,bool)": { + "details": "Returns all received attestation UUIDs.", + "params": { + "length": "The number of total members to retrieve.", + "recipient": "The recipient of the attestation.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getReceivedAttestationUUIDsCount(address,bytes32)": { + "details": "Returns the number of received attestation UUIDs.", + "params": { + "recipient": "The recipient of the attestation.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "getRelatedAttestationUUIDs(bytes32,uint256,uint256,bool)": { + "details": "Returns all attestations related to a specific attestation.", + "params": { + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "start": "The offset to start from.", + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getRelatedAttestationUUIDsCount(bytes32)": { + "details": "Returns the number of related attestation UUIDs.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "The number of related attestations." + } + }, + "getSchemaAttestationUUIDs(bytes32,uint256,uint256,bool)": { + "details": "Returns all per-schema attestation UUIDs.", + "params": { + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getSchemaAttestationUUIDsCount(bytes32)": { + "details": "Returns the number of per-schema attestation UUIDs.", + "params": { + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "getSentAttestationUUIDs(address,bytes32,uint256,uint256,bool)": { + "details": "Returns all sent attestation UUIDs.", + "params": { + "attester": "The attesting account.", + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getSentAttestationUUIDsCount(address,bytes32)": { + "details": "Returns the number of sent attestation UUIDs.", + "params": { + "recipient": "The recipient of the attestation.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "isAttestationActive(bytes32)": { + "details": "Checks whether an attestation is active.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "Whether an attestation is active." + } + }, + "isAttestationValid(bytes32)": { + "details": "Checks whether an attestation exists.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "Whether an attestation exists." + } + }, + "revoke(bytes32)": { + "details": "Revokes an existing attestation to a specific AS.", + "params": { + "uuid": "The UUID of the attestation to revoke." + } + }, + "revokeByDelegation(bytes32,address,uint8,bytes32,bytes32)": { + "details": "Attests to a specific AS using a provided EIP712 signature.", + "params": { + "attester": "The attesting account.", + "r": "The x-coordinate of the nonce R.", + "s": "The signature data.", + "uuid": "The UUID of the attestation to revoke.", + "v": "The recovery ID." + } + } + }, + "title": "TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 15692, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_relatedAttestations", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + { + "astId": 15699, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_receivedAttestations", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))" + }, + { + "astId": 15706, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_sentAttestations", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))" + }, + { + "astId": 15711, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_schemaAttestations", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + { + "astId": 15716, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_db", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_bytes32,t_struct(Attestation)48372_storage)" + }, + { + "astId": 15718, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_attestationsCount", + "offset": 0, + "slot": "5", + "type": "t_uint256" + }, + { + "astId": 15720, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_lastUUID", + "offset": 0, + "slot": "6", + "type": "t_bytes32" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "base": "t_bytes32", + "encoding": "dynamic_array", + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(bytes32 => bytes32[]))", + "numberOfBytes": "32", + "value": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes32[])", + "numberOfBytes": "32", + "value": "t_array(t_bytes32)dyn_storage" + }, + "t_mapping(t_bytes32,t_struct(Attestation)48372_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct IEAS.Attestation)", + "numberOfBytes": "32", + "value": "t_struct(Attestation)48372_storage" + }, + "t_struct(Attestation)48372_storage": { + "encoding": "inplace", + "label": "struct IEAS.Attestation", + "members": [ + { + "astId": 48355, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "uuid", + "offset": 0, + "slot": "0", + "type": "t_bytes32" + }, + { + "astId": 48357, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "schema", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + }, + { + "astId": 48359, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "recipient", + "offset": 0, + "slot": "2", + "type": "t_address" + }, + { + "astId": 48361, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "attester", + "offset": 0, + "slot": "3", + "type": "t_address" + }, + { + "astId": 48363, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "time", + "offset": 0, + "slot": "4", + "type": "t_uint256" + }, + { + "astId": 48365, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "expirationTime", + "offset": 0, + "slot": "5", + "type": "t_uint256" + }, + { + "astId": 48367, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "revocationTime", + "offset": 0, + "slot": "6", + "type": "t_uint256" + }, + { + "astId": 48369, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "refUUID", + "offset": 0, + "slot": "7", + "type": "t_bytes32" + }, + { + "astId": 48371, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "data", + "offset": 0, + "slot": "8", + "type": "t_bytes_storage" + } + ], + "numberOfBytes": "288" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/TellerASEIP712Verifier.json b/packages/contracts/deployments/bsc/TellerASEIP712Verifier.json new file mode 100644 index 000000000..d7ea0eee0 --- /dev/null +++ b/packages/contracts/deployments/bsc/TellerASEIP712Verifier.json @@ -0,0 +1,273 @@ +{ + "address": "0x0D1047229B9851eACE463Fb25f27982a5127c20F", + "abi": [ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "InvalidSignature", + "type": "error" + }, + { + "inputs": [], + "name": "ATTEST_TYPEHASH", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DOMAIN_SEPARATOR", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "REVOKE_TYPEHASH", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "attest", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "getNonce", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "revoke", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x16042bc42f64f5ee4da15f6170432004cf5410f0ae4207d6ceaa625c7f944d71", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x0D1047229B9851eACE463Fb25f27982a5127c20F", + "transactionIndex": 80, + "gasUsed": "451232", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x888be88b729abc5114d029bcd1d20cb8b4e09c9cda16b1ede67fc226393c4a4e", + "transactionHash": "0x16042bc42f64f5ee4da15f6170432004cf5410f0ae4207d6ceaa625c7f944d71", + "logs": [], + "blockNumber": 81086286, + "cumulativeGasUsed": "15393646", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"InvalidSignature\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ATTEST_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DOMAIN_SEPARATOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"REVOKE_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"attest\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"getNonce\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"revoke\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"attest(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)\":{\"details\":\"Verifies signed attestation.\",\"params\":{\"attester\":\"The attesting account.\",\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"r\":\"The x-coordinate of the nonce R.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"s\":\"The signature data.\",\"schema\":\"The UUID of the AS.\",\"v\":\"The recovery ID.\"}},\"constructor\":{\"details\":\"Creates a new EIP712Verifier instance.\"},\"getNonce(address)\":{\"details\":\"Returns the current nonce per-account.\",\"params\":{\"account\":\"The requested accunt.\"},\"returns\":{\"_0\":\"The current nonce.\"}},\"revoke(bytes32,address,uint8,bytes32,bytes32)\":{\"details\":\"Verifies signed revocations.\",\"params\":{\"attester\":\"The attesting account.\",\"r\":\"The x-coordinate of the nonce R.\",\"s\":\"The signature data.\",\"uuid\":\"The UUID of the attestation to revoke.\",\"v\":\"The recovery ID.\"}}},\"title\":\"EIP712 typed signatures verifier for EAS delegated attestations.\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerASEIP712Verifier.sol\":\"TellerASEIP712Verifier\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/EAS/TellerASEIP712Verifier.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\nimport \\\"../interfaces/IEASEIP712Verifier.sol\\\";\\n\\n/**\\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\\n */\\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\\n error InvalidSignature();\\n\\n string public constant VERSION = \\\"0.8\\\";\\n\\n // EIP712 domain separator, making signatures from different domains incompatible.\\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\\n\\n // The hash of the data type used to relay calls to the attest function. It's the value of\\n // keccak256(\\\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\\\").\\n bytes32 public constant ATTEST_TYPEHASH =\\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\\n\\n // The hash of the data type used to relay calls to the revoke function. It's the value of\\n // keccak256(\\\"Revoke(bytes32 uuid,uint256 nonce)\\\").\\n bytes32 public constant REVOKE_TYPEHASH =\\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\\n\\n // Replay protection nonces.\\n mapping(address => uint256) private _nonces;\\n\\n /**\\n * @dev Creates a new EIP712Verifier instance.\\n */\\n constructor() {\\n uint256 chainId;\\n // solhint-disable-next-line no-inline-assembly\\n assembly {\\n chainId := chainid()\\n }\\n\\n DOMAIN_SEPARATOR = keccak256(\\n abi.encode(\\n keccak256(\\n \\\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\\\"\\n ),\\n keccak256(bytes(\\\"EAS\\\")),\\n keccak256(bytes(VERSION)),\\n chainId,\\n address(this)\\n )\\n );\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\n */\\n function getNonce(address account)\\n external\\n view\\n override\\n returns (uint256)\\n {\\n return _nonces[account];\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\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 override {\\n bytes32 digest = keccak256(\\n abi.encodePacked(\\n \\\"\\\\x19\\\\x01\\\",\\n DOMAIN_SEPARATOR,\\n keccak256(\\n abi.encode(\\n ATTEST_TYPEHASH,\\n recipient,\\n schema,\\n expirationTime,\\n refUUID,\\n keccak256(data),\\n _nonces[attester]++\\n )\\n )\\n )\\n );\\n\\n address recoveredAddress = ecrecover(digest, v, r, s);\\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\\n revert InvalidSignature();\\n }\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\n */\\n function revoke(\\n bytes32 uuid,\\n address attester,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external override {\\n bytes32 digest = keccak256(\\n abi.encodePacked(\\n \\\"\\\\x19\\\\x01\\\",\\n DOMAIN_SEPARATOR,\\n keccak256(\\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\\n )\\n )\\n );\\n\\n address recoveredAddress = ecrecover(digest, v, r, s);\\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\\n revert InvalidSignature();\\n }\\n }\\n}\\n\",\"keccak256\":\"0x893f7174a3f30019e37a01b0bfd903caf18125259d13aedbad9212d402c4a4a1\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60a060405234801561001057600080fd5b5060408051808201825260038082526245415360e81b60209283015282518084018452908152620605c760eb1b9082015281517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f818301527f9fed719e0073f95229e6f4f6b6f28f260c524ab08aa40b11f9c28cb710d7c72a818401527f15e7a716d821b9602c70f6d0f574efbb8147fb465215d43354c7b3e69d03ed926060820152466080808301919091523060a0808401919091528451808403909101815260c09092019093528051910120908190526107256101076000396000818160d8015281816101a6015261031a01526107256000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c80636aeb49a51161005b5780636aeb49a5146100fa5780637e4a7d8f1461010d5780638a73222714610134578063ffa1ad741461015b57600080fd5b80631863f01d146100825780632d0335ab146100975780633644e515146100d3575b600080fd5b61009561009036600461051b565b61018a565b005b6100c06100a5366004610569565b6001600160a01b031660009081526020819052604090205490565b6040519081526020015b60405180910390f35b6100c07f000000000000000000000000000000000000000000000000000000000000000081565b61009561010836600461058b565b610316565b6100c07f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147681565b6100c07fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab81565b61017d604051806040016040528060038152602001620605c760eb1b81525081565b6040516100ca9190610661565b6001600160a01b038416600090815260208190526040812080547f0000000000000000000000000000000000000000000000000000000000000000917fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab918991856101f4836106b6565b9091555060408051602081019490945283019190915260608201526080016040516020818303038152906040528051906020012060405160200161024f92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa1580156102ba573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806102ef5750856001600160a01b0316816001600160a01b031614155b1561030d57604051638baa579f60e01b815260040160405180910390fd5b50505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000007f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147660001b8c8c8c8c8c8c6040516103719291906106df565b60408051918290039091206001600160a01b038d1660009081526020819052918220805491926103a0836106b6565b909155506040805160208101989098526001600160a01b03909616958701959095526060860193909352608085019190915260a084015260c083015260e0820152610100016040516020818303038152906040528051906020012060405160200161042292919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa15801561048d573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806104c25750856001600160a01b0316816001600160a01b031614155b156104e057604051638baa579f60e01b815260040160405180910390fd5b505050505050505050505050565b80356001600160a01b038116811461050557600080fd5b919050565b803560ff8116811461050557600080fd5b600080600080600060a0868803121561053357600080fd5b85359450610543602087016104ee565b93506105516040870161050a565b94979396509394606081013594506080013592915050565b60006020828403121561057b57600080fd5b610584826104ee565b9392505050565b6000806000806000806000806000806101208b8d0312156105ab57600080fd5b6105b48b6104ee565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff808211156105e657600080fd5b818d0191508d601f8301126105fa57600080fd5b81358181111561060957600080fd5b8e602082850101111561061b57600080fd5b60208301985080975050505061063360a08c016104ee565b935061064160c08c0161050a565b925060e08b013591506101008b013590509295989b9194979a5092959850565b600060208083528351808285015260005b8181101561068e57858101830151858201604001528201610672565b818111156106a0576000604083870101525b50601f01601f1916929092016040019392505050565b60006000198214156106d857634e487b7160e01b600052601160045260246000fd5b5060010190565b818382376000910190815291905056fea2646970667358221220d0c93b24e391671ef66b1f903855bc7ab981d375fc65451171489c87152dff3364736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061007d5760003560e01c80636aeb49a51161005b5780636aeb49a5146100fa5780637e4a7d8f1461010d5780638a73222714610134578063ffa1ad741461015b57600080fd5b80631863f01d146100825780632d0335ab146100975780633644e515146100d3575b600080fd5b61009561009036600461051b565b61018a565b005b6100c06100a5366004610569565b6001600160a01b031660009081526020819052604090205490565b6040519081526020015b60405180910390f35b6100c07f000000000000000000000000000000000000000000000000000000000000000081565b61009561010836600461058b565b610316565b6100c07f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147681565b6100c07fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab81565b61017d604051806040016040528060038152602001620605c760eb1b81525081565b6040516100ca9190610661565b6001600160a01b038416600090815260208190526040812080547f0000000000000000000000000000000000000000000000000000000000000000917fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab918991856101f4836106b6565b9091555060408051602081019490945283019190915260608201526080016040516020818303038152906040528051906020012060405160200161024f92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa1580156102ba573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806102ef5750856001600160a01b0316816001600160a01b031614155b1561030d57604051638baa579f60e01b815260040160405180910390fd5b50505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000007f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147660001b8c8c8c8c8c8c6040516103719291906106df565b60408051918290039091206001600160a01b038d1660009081526020819052918220805491926103a0836106b6565b909155506040805160208101989098526001600160a01b03909616958701959095526060860193909352608085019190915260a084015260c083015260e0820152610100016040516020818303038152906040528051906020012060405160200161042292919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa15801561048d573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806104c25750856001600160a01b0316816001600160a01b031614155b156104e057604051638baa579f60e01b815260040160405180910390fd5b505050505050505050505050565b80356001600160a01b038116811461050557600080fd5b919050565b803560ff8116811461050557600080fd5b600080600080600060a0868803121561053357600080fd5b85359450610543602087016104ee565b93506105516040870161050a565b94979396509394606081013594506080013592915050565b60006020828403121561057b57600080fd5b610584826104ee565b9392505050565b6000806000806000806000806000806101208b8d0312156105ab57600080fd5b6105b48b6104ee565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff808211156105e657600080fd5b818d0191508d601f8301126105fa57600080fd5b81358181111561060957600080fd5b8e602082850101111561061b57600080fd5b60208301985080975050505061063360a08c016104ee565b935061064160c08c0161050a565b925060e08b013591506101008b013590509295989b9194979a5092959850565b600060208083528351808285015260005b8181101561068e57858101830151858201604001528201610672565b818111156106a0576000604083870101525b50601f01601f1916929092016040019392505050565b60006000198214156106d857634e487b7160e01b600052601160045260246000fd5b5060010190565b818382376000910190815291905056fea2646970667358221220d0c93b24e391671ef66b1f903855bc7ab981d375fc65451171489c87152dff3364736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "attest(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)": { + "details": "Verifies signed attestation.", + "params": { + "attester": "The attesting account.", + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "r": "The x-coordinate of the nonce R.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "s": "The signature data.", + "schema": "The UUID of the AS.", + "v": "The recovery ID." + } + }, + "constructor": { + "details": "Creates a new EIP712Verifier instance." + }, + "getNonce(address)": { + "details": "Returns the current nonce per-account.", + "params": { + "account": "The requested accunt." + }, + "returns": { + "_0": "The current nonce." + } + }, + "revoke(bytes32,address,uint8,bytes32,bytes32)": { + "details": "Verifies signed revocations.", + "params": { + "attester": "The attesting account.", + "r": "The x-coordinate of the nonce R.", + "s": "The signature data.", + "uuid": "The UUID of the attestation to revoke.", + "v": "The recovery ID." + } + } + }, + "title": "EIP712 typed signatures verifier for EAS delegated attestations.", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 16574, + "contract": "contracts/EAS/TellerASEIP712Verifier.sol:TellerASEIP712Verifier", + "label": "_nonces", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_uint256)" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_uint256)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/TellerASRegistry.json b/packages/contracts/deployments/bsc/TellerASRegistry.json new file mode 100644 index 000000000..df2a50b88 --- /dev/null +++ b/packages/contracts/deployments/bsc/TellerASRegistry.json @@ -0,0 +1,285 @@ +{ + "address": "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", + "abi": [ + { + "inputs": [], + "name": "AlreadyExists", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "schema", + "type": "bytes" + }, + { + "indexed": false, + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "attester", + "type": "address" + } + ], + "name": "Registered", + "type": "event" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getAS", + "outputs": [ + { + "components": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + }, + { + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "schema", + "type": "bytes" + } + ], + "internalType": "struct IASRegistry.ASRecord", + "name": "", + "type": "tuple" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getASCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "schema", + "type": "bytes" + }, + { + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + } + ], + "name": "register", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xb28684737cb46ffda6c378c31542a745280bd69d11dd40baa6bde5f38c2e00b4", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", + "transactionIndex": 67, + "gasUsed": "415650", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xfaabf8079680c6dc389d73624ec1f6f723c7bc09add2aef363d30fdbfd76cb87", + "transactionHash": "0xb28684737cb46ffda6c378c31542a745280bd69d11dd40baa6bde5f38c2e00b4", + "logs": [], + "blockNumber": 81086284, + "cumulativeGasUsed": "13391445", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"}],\"name\":\"Registered\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getAS\",\"outputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"}],\"internalType\":\"struct IASRegistry.ASRecord\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getASCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"},{\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"}],\"name\":\"register\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"getAS(bytes32)\":{\"details\":\"Returns an existing AS by UUID\",\"params\":{\"uuid\":\"The UUID of the AS to retrieve.\"},\"returns\":{\"_0\":\"The AS data members.\"}},\"getASCount()\":{\"details\":\"Returns the global counter for the total number of attestations\",\"returns\":{\"_0\":\"The global counter for the total number of attestations.\"}},\"register(bytes,address)\":{\"details\":\"Submits and reserve a new AS\",\"params\":{\"resolver\":\"An optional AS schema resolver.\",\"schema\":\"The AS data schema.\"},\"returns\":{\"_0\":\"The UUID of the new AS.\"}}},\"title\":\"The global AS registry.\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerASRegistry.sol\":\"TellerASRegistry\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/EAS/TellerASRegistry.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\nimport \\\"../Types.sol\\\";\\nimport \\\"../interfaces/IASRegistry.sol\\\";\\nimport \\\"../interfaces/IASResolver.sol\\\";\\n\\n/**\\n * @title The global AS registry.\\n */\\ncontract TellerASRegistry is IASRegistry {\\n error AlreadyExists();\\n\\n string public constant VERSION = \\\"0.8\\\";\\n\\n // The global mapping between AS records and their IDs.\\n mapping(bytes32 => ASRecord) private _registry;\\n\\n // The global counter for the total number of attestations.\\n uint256 private _asCount;\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function register(bytes calldata schema, IASResolver resolver)\\n external\\n override\\n returns (bytes32)\\n {\\n uint256 index = ++_asCount;\\n\\n ASRecord memory asRecord = ASRecord({\\n uuid: EMPTY_UUID,\\n index: index,\\n schema: schema,\\n resolver: resolver\\n });\\n\\n bytes32 uuid = _getUUID(asRecord);\\n if (_registry[uuid].uuid != EMPTY_UUID) {\\n revert AlreadyExists();\\n }\\n\\n asRecord.uuid = uuid;\\n _registry[uuid] = asRecord;\\n\\n emit Registered(uuid, index, schema, resolver, msg.sender);\\n\\n return uuid;\\n }\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function getAS(bytes32 uuid)\\n external\\n view\\n override\\n returns (ASRecord memory)\\n {\\n return _registry[uuid];\\n }\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function getASCount() external view override returns (uint256) {\\n return _asCount;\\n }\\n\\n /**\\n * @dev Calculates a UUID for a given AS.\\n *\\n * @param asRecord The input AS.\\n *\\n * @return AS UUID.\\n */\\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\\n }\\n}\\n\",\"keccak256\":\"0x1d5782c3bb5ea52db95c8ce6d7ff6d20382bae8ca574614cfbaa45c05f93f13c\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b5061068e806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806372487d5214610051578063a99e7e291461007a578063d96250641461009b578063ffa1ad74146100a3575b600080fd5b61006461005f36600461040f565b6100d2565b6040516100719190610484565b60405180910390f35b61008d6100883660046104cd565b6101d3565b604051908152602001610071565b60015461008d565b6100c5604051806040016040528060038152602001620605c760eb1b81525081565b604051610071919061055c565b60408051608081018252600080825260208201819052918101919091526060808201526000828152602081815260409182902082516080810184528154815260018201546001600160a01b03169281019290925260028101549282019290925260038201805491929160608401919061014a90610576565b80601f016020809104026020016040519081016040528092919081815260200182805461017690610576565b80156101c35780601f10610198576101008083540402835291602001916101c3565b820191906000526020600020905b8154815290600101906020018083116101a657829003601f168201915b5050505050815250509050919050565b6000806001600081546101e5906105b1565b9190508190559050600060405180608001604052806000801b8152602001856001600160a01b0316815260200183815260200187878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350915061025f90508261033c565b6000818152602081905260409020549091501561028f5760405163119b4fd360e11b815260040160405180910390fd5b8082526000818152602081815260409182902084518155818501516001820180546001600160a01b0319166001600160a01b03909216919091179055918401516002830155606084015180518593926102ef926003850192910190610376565b5090505082817f51a1a037ef8a642f8b5528429785b5a54e6ee54fb2d2db4b4a44480b5302d55b8989893360405161032a94939291906105da565b60405180910390a39695505050505050565b600081606001518260200151604051602001610359929190610621565b604051602081830303815290604052805190602001209050919050565b82805461038290610576565b90600052602060002090601f0160209004810192826103a457600085556103ea565b82601f106103bd57805160ff19168380011785556103ea565b828001600101855582156103ea579182015b828111156103ea5782518255916020019190600101906103cf565b506103f69291506103fa565b5090565b5b808211156103f657600081556001016103fb565b60006020828403121561042157600080fd5b5035919050565b60005b8381101561044357818101518382015260200161042b565b83811115610452576000848401525b50505050565b60008151808452610470816020860160208601610428565b601f01601f19169290920160200192915050565b602081528151602082015260018060a01b03602083015116604082015260408201516060820152600060608301516080808401526104c560a0840182610458565b949350505050565b6000806000604084860312156104e257600080fd5b833567ffffffffffffffff808211156104fa57600080fd5b818601915086601f83011261050e57600080fd5b81358181111561051d57600080fd5b87602082850101111561052f57600080fd5b602092830195509350508401356001600160a01b038116811461055157600080fd5b809150509250925092565b60208152600061056f6020830184610458565b9392505050565b600181811c9082168061058a57607f821691505b602082108114156105ab57634e487b7160e01b600052602260045260246000fd5b50919050565b60006000198214156105d357634e487b7160e01b600052601160045260246000fd5b5060010190565b6060815283606082015283856080830137600060808583018101919091526001600160a01b039384166020830152919092166040830152601f909201601f19160101919050565b60008351610633818460208801610428565b60609390931b6bffffffffffffffffffffffff1916919092019081526014019291505056fea2646970667358221220f4080119bbc4198852f1eee79e8e0c663b8e4189faee0f706f0d5bbdbec3e88a64736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061004c5760003560e01c806372487d5214610051578063a99e7e291461007a578063d96250641461009b578063ffa1ad74146100a3575b600080fd5b61006461005f36600461040f565b6100d2565b6040516100719190610484565b60405180910390f35b61008d6100883660046104cd565b6101d3565b604051908152602001610071565b60015461008d565b6100c5604051806040016040528060038152602001620605c760eb1b81525081565b604051610071919061055c565b60408051608081018252600080825260208201819052918101919091526060808201526000828152602081815260409182902082516080810184528154815260018201546001600160a01b03169281019290925260028101549282019290925260038201805491929160608401919061014a90610576565b80601f016020809104026020016040519081016040528092919081815260200182805461017690610576565b80156101c35780601f10610198576101008083540402835291602001916101c3565b820191906000526020600020905b8154815290600101906020018083116101a657829003601f168201915b5050505050815250509050919050565b6000806001600081546101e5906105b1565b9190508190559050600060405180608001604052806000801b8152602001856001600160a01b0316815260200183815260200187878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350915061025f90508261033c565b6000818152602081905260409020549091501561028f5760405163119b4fd360e11b815260040160405180910390fd5b8082526000818152602081815260409182902084518155818501516001820180546001600160a01b0319166001600160a01b03909216919091179055918401516002830155606084015180518593926102ef926003850192910190610376565b5090505082817f51a1a037ef8a642f8b5528429785b5a54e6ee54fb2d2db4b4a44480b5302d55b8989893360405161032a94939291906105da565b60405180910390a39695505050505050565b600081606001518260200151604051602001610359929190610621565b604051602081830303815290604052805190602001209050919050565b82805461038290610576565b90600052602060002090601f0160209004810192826103a457600085556103ea565b82601f106103bd57805160ff19168380011785556103ea565b828001600101855582156103ea579182015b828111156103ea5782518255916020019190600101906103cf565b506103f69291506103fa565b5090565b5b808211156103f657600081556001016103fb565b60006020828403121561042157600080fd5b5035919050565b60005b8381101561044357818101518382015260200161042b565b83811115610452576000848401525b50505050565b60008151808452610470816020860160208601610428565b601f01601f19169290920160200192915050565b602081528151602082015260018060a01b03602083015116604082015260408201516060820152600060608301516080808401526104c560a0840182610458565b949350505050565b6000806000604084860312156104e257600080fd5b833567ffffffffffffffff808211156104fa57600080fd5b818601915086601f83011261050e57600080fd5b81358181111561051d57600080fd5b87602082850101111561052f57600080fd5b602092830195509350508401356001600160a01b038116811461055157600080fd5b809150509250925092565b60208152600061056f6020830184610458565b9392505050565b600181811c9082168061058a57607f821691505b602082108114156105ab57634e487b7160e01b600052602260045260246000fd5b50919050565b60006000198214156105d357634e487b7160e01b600052601160045260246000fd5b5060010190565b6060815283606082015283856080830137600060808583018101919091526001600160a01b039384166020830152919092166040830152601f909201601f19160101919050565b60008351610633818460208801610428565b60609390931b6bffffffffffffffffffffffff1916919092019081526014019291505056fea2646970667358221220f4080119bbc4198852f1eee79e8e0c663b8e4189faee0f706f0d5bbdbec3e88a64736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "getAS(bytes32)": { + "details": "Returns an existing AS by UUID", + "params": { + "uuid": "The UUID of the AS to retrieve." + }, + "returns": { + "_0": "The AS data members." + } + }, + "getASCount()": { + "details": "Returns the global counter for the total number of attestations", + "returns": { + "_0": "The global counter for the total number of attestations." + } + }, + "register(bytes,address)": { + "details": "Submits and reserve a new AS", + "params": { + "resolver": "An optional AS schema resolver.", + "schema": "The AS data schema." + }, + "returns": { + "_0": "The UUID of the new AS." + } + } + }, + "title": "The global AS registry.", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 16780, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "_registry", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(ASRecord)48152_storage)" + }, + { + "astId": 16782, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "_asCount", + "offset": 0, + "slot": "1", + "type": "t_uint256" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_contract(IASResolver)48219": { + "encoding": "inplace", + "label": "contract IASResolver", + "numberOfBytes": "20" + }, + "t_mapping(t_bytes32,t_struct(ASRecord)48152_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct IASRegistry.ASRecord)", + "numberOfBytes": "32", + "value": "t_struct(ASRecord)48152_storage" + }, + "t_struct(ASRecord)48152_storage": { + "encoding": "inplace", + "label": "struct IASRegistry.ASRecord", + "members": [ + { + "astId": 48144, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "uuid", + "offset": 0, + "slot": "0", + "type": "t_bytes32" + }, + { + "astId": 48147, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "resolver", + "offset": 0, + "slot": "1", + "type": "t_contract(IASResolver)48219" + }, + { + "astId": 48149, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "index", + "offset": 0, + "slot": "2", + "type": "t_uint256" + }, + { + "astId": 48151, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "schema", + "offset": 0, + "slot": "3", + "type": "t_bytes_storage" + } + ], + "numberOfBytes": "128" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/TellerV2.json b/packages/contracts/deployments/bsc/TellerV2.json new file mode 100644 index 000000000..3969dfa2c --- /dev/null +++ b/packages/contracts/deployments/bsc/TellerV2.json @@ -0,0 +1,1761 @@ +{ + "address": "0x90D08f8Df66dFdE93801783FF7A36876453DAE75", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "trustedForwarder" + } + ] + }, + { + "type": "error", + "name": "ActionNotAllowed", + "inputs": [ + { + "type": "uint256", + "name": "bidId" + }, + { + "type": "string", + "name": "action" + }, + { + "type": "string", + "name": "message" + } + ] + }, + { + "type": "error", + "name": "PaymentNotMinimum", + "inputs": [ + { + "type": "uint256", + "name": "bidId" + }, + { + "type": "uint256", + "name": "payment" + }, + { + "type": "uint256", + "name": "minimumOwed" + } + ] + }, + { + "type": "error", + "name": "SafeERC20FailedOperation", + "inputs": [ + { + "type": "address", + "name": "token" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "AcceptedBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "lender", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CancelledBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "FeePaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "string", + "name": "feeType", + "indexed": true + }, + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanClosed", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepayment", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketForwarderApproved", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": true + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketForwarderRenounced", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": true + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketOwnerCancelledBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ProtocolFeeSet", + "inputs": [ + { + "type": "uint16", + "name": "newFee", + "indexed": false + }, + { + "type": "uint16", + "name": "oldFee", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SubmittedBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": false + }, + { + "type": "bytes32", + "name": "metadataURI", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "TrustedMarketForwarderSet", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": false + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CURRENT_CODE_VERSION", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "LIQUIDATION_DELAY", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "__lenderVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "__totalVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approveMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "bidDefaultDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidExpirationTime", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidPaymentCycleType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketplaceId" + }, + { + "type": "bytes32", + "name": "_metadataURI" + }, + { + "type": "tuple", + "name": "loanDetails", + "components": [ + { + "type": "address", + "name": "lendingToken" + }, + { + "type": "uint256", + "name": "principal" + }, + { + "type": "tuple", + "name": "totalRepaid", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + }, + { + "type": "uint32", + "name": "timestamp" + }, + { + "type": "uint32", + "name": "acceptedTimestamp" + }, + { + "type": "uint32", + "name": "lastRepaidTimestamp" + }, + { + "type": "uint32", + "name": "loanDuration" + } + ] + }, + { + "type": "tuple", + "name": "terms", + "components": [ + { + "type": "uint256", + "name": "paymentCycleAmount" + }, + { + "type": "uint32", + "name": "paymentCycle" + }, + { + "type": "uint16", + "name": "APR" + } + ] + }, + { + "type": "uint8", + "name": "state" + }, + { + "type": "uint8", + "name": "paymentType" + } + ] + }, + { + "type": "function", + "name": "borrowerBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateAmountDue", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "tuple", + "name": "due", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + } + ] + }, + { + "type": "function", + "name": "calculateAmountOwed", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "tuple", + "name": "owed", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + } + ] + }, + { + "type": "function", + "name": "calculateNextDueDate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "dueDate_" + } + ] + }, + { + "type": "function", + "name": "cancelBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "claimLoanNFT", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "collateralManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "escrowVault", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBidState", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBorrowerActiveLoanIds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBorrowerLoanIds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getEscrowVault", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLoanBorrower", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower_" + } + ] + }, + { + "type": "function", + "name": "getLoanDefaultTimestamp", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLoanLender", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "lender_" + } + ] + }, + { + "type": "function", + "name": "getLoanLendingToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "token_" + } + ] + }, + { + "type": "function", + "name": "getLoanMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ] + }, + { + "type": "function", + "name": "getLoanSummary", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint32", + "name": "acceptedTimestamp" + }, + { + "type": "uint32", + "name": "lastRepaidTimestamp" + }, + { + "type": "uint8", + "name": "bidState" + } + ] + }, + { + "type": "function", + "name": "getProtocolFeeRecipient", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getProtocolPausingManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getRepaymentListenerForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "hasApprovedMarketForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + }, + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "_protocolFee" + }, + { + "type": "address", + "name": "_marketRegistry" + }, + { + "type": "address", + "name": "_reputationManager" + }, + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "address", + "name": "_collateralManager" + }, + { + "type": "address", + "name": "_lenderManager" + }, + { + "type": "address", + "name": "_escrowVault" + }, + { + "type": "address", + "name": "_protocolPausingManager" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isLoanDefaulted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isLoanExpired", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isLoanLiquidateable", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isPaymentLate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isTrustedForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "forwarder" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isTrustedMarketForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_trustedMarketForwarder" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastRepaidTimestamp", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "amountToProtocol" + }, + { + "type": "uint256", + "name": "amountToMarketplace" + }, + { + "type": "uint256", + "name": "amountToBorrower" + } + ] + }, + { + "type": "function", + "name": "lenderCloseLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderCloseLoanWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralRecipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderCommitmentForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateLoanFull", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidateLoanFullWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketOwnerCancelBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "protocolFee", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanFull", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanFullWithoutCollateralWithdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanMinimum", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanWithoutCollateralWithdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repaymentListenerForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "reputationManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "setProtocolFee", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "newFee" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setProtocolFeeRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setRepaymentListenerForBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_listener" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setTrustedMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "submitBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lendingToken" + }, + { + "type": "uint256", + "name": "_marketplaceId" + }, + { + "type": "uint256", + "name": "_principal" + }, + { + "type": "uint32", + "name": "_duration" + }, + { + "type": "uint16", + "name": "_APR" + }, + { + "type": "string", + "name": "_metadataURI" + }, + { + "type": "address", + "name": "_receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId_" + } + ] + }, + { + "type": "function", + "name": "submitBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lendingToken" + }, + { + "type": "uint256", + "name": "_marketplaceId" + }, + { + "type": "uint256", + "name": "_principal" + }, + { + "type": "uint32", + "name": "_duration" + }, + { + "type": "uint16", + "name": "_APR" + }, + { + "type": "string", + "name": "_metadataURI" + }, + { + "type": "address", + "name": "_receiver" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId_" + } + ] + }, + { + "type": "function", + "name": "totalVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "uris", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "version", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + } + ], + "transactionHash": "0x1fc7bcdf09102a0b3143d8a87ec810fc68f3a7e531781b523d66f6bfcdb865bc", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0xf7B14778035fEAF44540A0bC1D4ED859bCB28229" +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/TimelockController.json b/packages/contracts/deployments/bsc/TimelockController.json new file mode 100644 index 000000000..58ce31657 --- /dev/null +++ b/packages/contracts/deployments/bsc/TimelockController.json @@ -0,0 +1,1246 @@ +{ + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "minDelay", + "type": "uint256" + }, + { + "internalType": "address[]", + "name": "proposers", + "type": "address[]" + }, + { + "internalType": "address[]", + "name": "executors", + "type": "address[]" + }, + { + "internalType": "address", + "name": "admin", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "CallExecuted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "CallScheduled", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "Cancelled", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldDuration", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newDuration", + "type": "uint256" + } + ], + "name": "MinDelayChange", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "previousAdminRole", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "newAdminRole", + "type": "bytes32" + } + ], + "name": "RoleAdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleGranted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleRevoked", + "type": "event" + }, + { + "inputs": [], + "name": "CANCELLER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DEFAULT_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "EXECUTOR_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "PROPOSER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "TIMELOCK_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "cancel", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "payload", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "execute", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "executeBatch", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [], + "name": "getMinDelay", + "outputs": [ + { + "internalType": "uint256", + "name": "duration", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + } + ], + "name": "getRoleAdmin", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "getTimestamp", + "outputs": [ + { + "internalType": "uint256", + "name": "timestamp", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "grantRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "hasRole", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "hashOperation", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "hashOperationBatch", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperation", + "outputs": [ + { + "internalType": "bool", + "name": "registered", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationDone", + "outputs": [ + { + "internalType": "bool", + "name": "done", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationPending", + "outputs": [ + { + "internalType": "bool", + "name": "pending", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationReady", + "outputs": [ + { + "internalType": "bool", + "name": "ready", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256[]", + "name": "", + "type": "uint256[]" + }, + { + "internalType": "uint256[]", + "name": "", + "type": "uint256[]" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155BatchReceived", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC721Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "renounceRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "revokeRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "schedule", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "scheduleBatch", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes4", + "name": "interfaceId", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newDelay", + "type": "uint256" + } + ], + "name": "updateDelay", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ], + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "transactionIndex": 26, + "gasUsed": "1966813", + "logsBloom": "0x000000048000000008020000000000000a0000000000000000000000000000020000000000000040000020000001000000000000000000000200000012200000000000000000000000040010000080800000000000000000000000000001000000000000020000400000000000000800000000000020000000020000000000000000020000000000000000000000000000000000000000080000000000000000000000000020000000000000000000000000000000000000001000000000000000000000000000004000000000000000000200000000000100000100200020000000000000001000000000000000000000000010000000000000000000000000", + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62", + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "logs": [ + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 101, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 102, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 103, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 104, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x000000000000000000000000bf4e3fea276057d0b26f52141557c835a7e2d534", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 105, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x000000000000000000000000058057c8a9eb3b93d9f3638d047c98034f45f95e", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 106, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1", + "0x000000000000000000000000058057c8a9eb3b93d9f3638d047c98034f45f95e", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 107, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "0x000000000000000000000000058057c8a9eb3b93d9f3638d047c98034f45f95e", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 108, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63", + "0x000000000000000000000000058057c8a9eb3b93d9f3638d047c98034f45f95e", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 109, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + }, + { + "transactionIndex": 26, + "blockNumber": 81085166, + "transactionHash": "0x10b37527ed06c099c4b705ff9bd743821fc96e827fa9764fe0d6b49fa8a072e2", + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "topics": [ + "0x11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4", + "logIndex": 110, + "blockHash": "0x1b1fdc57caca5a15051a0a97f1fa3c087cf732dd5427b1126970fbadc26c3e62" + } + ], + "blockNumber": 81085166, + "cumulativeGasUsed": "8588083", + "status": 1, + "byzantium": true + }, + "args": [ + 180, + [ + "0x058057c8A9Eb3B93d9F3638d047C98034F45f95E" + ], + [ + "0x058057c8A9Eb3B93d9F3638d047C98034F45f95E" + ], + "0x058057c8A9Eb3B93d9F3638d047C98034F45f95E" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"minDelay\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"proposers\",\"type\":\"address[]\"},{\"internalType\":\"address[]\",\"name\":\"executors\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"admin\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"CallExecuted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"CallScheduled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"Cancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"oldDuration\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"newDuration\",\"type\":\"uint256\"}],\"name\":\"MinDelayChange\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CANCELLER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"EXECUTOR_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PROPOSER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"TIMELOCK_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"cancel\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"payload\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"execute\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"executeBatch\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getMinDelay\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"duration\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"getTimestamp\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"timestamp\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"hashOperation\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"hashOperationBatch\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperation\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"registered\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationDone\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"done\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationPending\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"pending\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationReady\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"ready\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155BatchReceived\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC721Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"schedule\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"scheduleBatch\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"newDelay\",\"type\":\"uint256\"}],\"name\":\"updateDelay\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied. By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer. _Available since v3.3._\",\"events\":{\"CallExecuted(bytes32,uint256,address,uint256,bytes)\":{\"details\":\"Emitted when a call is performed as part of operation `id`.\"},\"CallScheduled(bytes32,uint256,address,uint256,bytes,bytes32,uint256)\":{\"details\":\"Emitted when a call is scheduled as part of operation `id`.\"},\"Cancelled(bytes32)\":{\"details\":\"Emitted when operation `id` is cancelled.\"},\"MinDelayChange(uint256,uint256)\":{\"details\":\"Emitted when the minimum delay for future operations is modified.\"}},\"kind\":\"dev\",\"methods\":{\"cancel(bytes32)\":{\"details\":\"Cancel an operation. Requirements: - the caller must have the 'canceller' role.\"},\"constructor\":{\"details\":\"Initializes the contract with the following parameters: - `minDelay`: initial minimum delay for operations - `proposers`: accounts to be granted proposer and canceller roles - `executors`: accounts to be granted executor role - `admin`: optional account to be granted admin role; disable with zero address IMPORTANT: The optional admin can aid with initial configuration of roles after deployment without being subject to delay, but this role should be subsequently renounced in favor of administration through timelocked proposals. Previous versions of this contract would assign this admin to the deployer automatically and should be renounced as well.\"},\"execute(address,uint256,bytes,bytes32,bytes32)\":{\"details\":\"Execute an (ready) operation containing a single transaction. Emits a {CallExecuted} event. Requirements: - the caller must have the 'executor' role.\"},\"executeBatch(address[],uint256[],bytes[],bytes32,bytes32)\":{\"details\":\"Execute an (ready) operation containing a batch of transactions. Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' role.\"},\"getMinDelay()\":{\"details\":\"Returns the minimum delay for an operation to become valid. This value can be changed by executing an operation that calls `updateDelay`.\"},\"getRoleAdmin(bytes32)\":{\"details\":\"Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}.\"},\"getTimestamp(bytes32)\":{\"details\":\"Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations).\"},\"grantRole(bytes32,address)\":{\"details\":\"Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event.\"},\"hasRole(bytes32,address)\":{\"details\":\"Returns `true` if `account` has been granted `role`.\"},\"hashOperation(address,uint256,bytes,bytes32,bytes32)\":{\"details\":\"Returns the identifier of an operation containing a single transaction.\"},\"hashOperationBatch(address[],uint256[],bytes[],bytes32,bytes32)\":{\"details\":\"Returns the identifier of an operation containing a batch of transactions.\"},\"isOperation(bytes32)\":{\"details\":\"Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations.\"},\"isOperationDone(bytes32)\":{\"details\":\"Returns whether an operation is done or not.\"},\"isOperationPending(bytes32)\":{\"details\":\"Returns whether an operation is pending or not.\"},\"isOperationReady(bytes32)\":{\"details\":\"Returns whether an operation is ready or not.\"},\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\":{\"details\":\"See {IERC1155Receiver-onERC1155BatchReceived}.\"},\"onERC1155Received(address,address,uint256,uint256,bytes)\":{\"details\":\"See {IERC1155Receiver-onERC1155Received}.\"},\"onERC721Received(address,address,uint256,bytes)\":{\"details\":\"See {IERC721Receiver-onERC721Received}.\"},\"renounceRole(bytes32,address)\":{\"details\":\"Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event.\"},\"revokeRole(bytes32,address)\":{\"details\":\"Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event.\"},\"schedule(address,uint256,bytes,bytes32,bytes32,uint256)\":{\"details\":\"Schedule an operation containing a single transaction. Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role.\"},\"scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256)\":{\"details\":\"Schedule an operation containing a batch of transactions. Emits one {CallScheduled} event per transaction in the batch. Requirements: - the caller must have the 'proposer' role.\"},\"supportsInterface(bytes4)\":{\"details\":\"See {IERC165-supportsInterface}.\"},\"updateDelay(uint256)\":{\"details\":\"Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/admin/TimelockController.sol\":\"TimelockController\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/admin/TimelockController.sol\":{\"content\":\"/**\\n *Submitted for verification at Etherscan.io on 2023-02-08\\n*/\\n\\n//SPDX-License-Identifier: MIT\\n\\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev External interface of AccessControl declared to support ERC165 detection.\\n */\\ninterface IAccessControl {\\n /**\\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\\n *\\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\\n * {RoleAdminChanged} not being emitted signaling this.\\n *\\n * _Available since v3.1._\\n */\\n event RoleAdminChanged(\\n bytes32 indexed role,\\n bytes32 indexed previousAdminRole,\\n bytes32 indexed newAdminRole\\n );\\n\\n /**\\n * @dev Emitted when `account` is granted `role`.\\n *\\n * `sender` is the account that originated the contract call, an admin role\\n * bearer except when using {AccessControl-_setupRole}.\\n */\\n event RoleGranted(\\n bytes32 indexed role,\\n address indexed account,\\n address indexed sender\\n );\\n\\n /**\\n * @dev Emitted when `account` is revoked `role`.\\n *\\n * `sender` is the account that originated the contract call:\\n * - if using `revokeRole`, it is the admin role bearer\\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\\n */\\n event RoleRevoked(\\n bytes32 indexed role,\\n address indexed account,\\n address indexed sender\\n );\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account)\\n external\\n view\\n returns (bool);\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function grantRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function revokeRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been granted `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n */\\n function renounceRole(bytes32 role, address account) external;\\n}\\n\\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\\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\\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\\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 IERC165 {\\n /**\\n * @dev Returns true if this contract implements the interface defined by\\n * `interfaceId`. See the corresponding\\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\\n * to learn more about how these ids are created.\\n *\\n * This function call must use less than 30 000 gas.\\n */\\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\\n}\\n\\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Implementation of the {IERC165} interface.\\n *\\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\\n * for the additional interface id that will be supported. For example:\\n *\\n * ```solidity\\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\\n * }\\n * ```\\n *\\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\\n */\\nabstract contract ERC165 is IERC165 {\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return interfaceId == type(IERC165).interfaceId;\\n }\\n}\\n\\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\\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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = sqrt(a);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log2(value);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log10(value);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log256(value);\\n return\\n result +\\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\\n\\npragma solidity ^0.8.0;\\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)\\n internal\\n pure\\n returns (string memory)\\n {\\n bytes memory buffer = new bytes(2 * length + 2);\\n buffer[0] = \\\"0\\\";\\n buffer[1] = \\\"x\\\";\\n for (uint256 i = 2 * length + 1; i > 1; --i) {\\n buffer[i] = _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\\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Contract module that allows children to implement role-based access\\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\\n * members except through off-chain means by accessing the contract event logs. Some\\n * applications may benefit from on-chain enumerability, for those cases see\\n * {AccessControlEnumerable}.\\n *\\n * Roles are referred to by their `bytes32` identifier. These should be exposed\\n * in the external API and be unique. The best way to achieve this is by\\n * using `public constant` hash digests:\\n *\\n * ```\\n * bytes32 public constant MY_ROLE = keccak256(\\\"MY_ROLE\\\");\\n * ```\\n *\\n * Roles can be used to represent a set of permissions. To restrict access to a\\n * function call, use {hasRole}:\\n *\\n * ```\\n * function foo() public {\\n * require(hasRole(MY_ROLE, msg.sender));\\n * ...\\n * }\\n * ```\\n *\\n * Roles can be granted and revoked dynamically via the {grantRole} and\\n * {revokeRole} functions. Each role has an associated admin role, and only\\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\\n *\\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\\n * that only accounts with this role will be able to grant or revoke other\\n * roles. More complex role relationships can be created by using\\n * {_setRoleAdmin}.\\n *\\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\\n * grant and revoke this role. Extra precautions should be taken to secure\\n * accounts that have been granted it.\\n */\\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\\n struct RoleData {\\n mapping(address => bool) members;\\n bytes32 adminRole;\\n }\\n\\n mapping(bytes32 => RoleData) private _roles;\\n\\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\\n\\n /**\\n * @dev Modifier that checks that an account has a specific role. Reverts\\n * with a standardized message including the required role.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n *\\n * _Available since v4.1._\\n */\\n modifier onlyRole(bytes32 role) {\\n _checkRole(role);\\n _;\\n }\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return\\n interfaceId == type(IAccessControl).interfaceId ||\\n super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return _roles[role].members[account];\\n }\\n\\n /**\\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\\n * Overriding this function changes the behavior of the {onlyRole} modifier.\\n *\\n * Format of the revert message is described in {_checkRole}.\\n *\\n * _Available since v4.6._\\n */\\n function _checkRole(bytes32 role) internal view virtual {\\n _checkRole(role, _msgSender());\\n }\\n\\n /**\\n * @dev Revert with a standard message if `account` is missing `role`.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n */\\n function _checkRole(bytes32 role, address account) internal view virtual {\\n if (!hasRole(role, account)) {\\n revert(\\n string(\\n abi.encodePacked(\\n \\\"AccessControl: account \\\",\\n Strings.toHexString(account),\\n \\\" is missing role \\\",\\n Strings.toHexString(uint256(role), 32)\\n )\\n )\\n );\\n }\\n }\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role)\\n public\\n view\\n virtual\\n override\\n returns (bytes32)\\n {\\n return _roles[role].adminRole;\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function grantRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n onlyRole(getRoleAdmin(role))\\n {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function revokeRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n onlyRole(getRoleAdmin(role))\\n {\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function renounceRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n {\\n require(\\n account == _msgSender(),\\n \\\"AccessControl: can only renounce roles for self\\\"\\n );\\n\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event. Note that unlike {grantRole}, this function doesn't perform any\\n * checks on the calling account.\\n *\\n * May emit a {RoleGranted} event.\\n *\\n * [WARNING]\\n * ====\\n * This function should only be called from the constructor when setting\\n * up the initial roles for the system.\\n *\\n * Using this function in any other way is effectively circumventing the admin\\n * system imposed by {AccessControl}.\\n * ====\\n *\\n * NOTE: This function is deprecated in favor of {_grantRole}.\\n */\\n function _setupRole(bytes32 role, address account) internal virtual {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Sets `adminRole` as ``role``'s admin role.\\n *\\n * Emits a {RoleAdminChanged} event.\\n */\\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\\n bytes32 previousAdminRole = getRoleAdmin(role);\\n _roles[role].adminRole = adminRole;\\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function _grantRole(bytes32 role, address account) internal virtual {\\n if (!hasRole(role, account)) {\\n _roles[role].members[account] = true;\\n emit RoleGranted(role, account, _msgSender());\\n }\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function _revokeRole(bytes32 role, address account) internal virtual {\\n if (hasRole(role, account)) {\\n _roles[role].members[account] = false;\\n emit RoleRevoked(role, account, _msgSender());\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev _Available since v3.1._\\n */\\ninterface IERC1155Receiver is IERC165 {\\n /**\\n * @dev Handles the receipt of a single ERC1155 token type. This function is\\n * called at the end of a `safeTransferFrom` after the balance has been updated.\\n *\\n * NOTE: To accept the transfer, this must return\\n * `bytes4(keccak256(\\\"onERC1155Received(address,address,uint256,uint256,bytes)\\\"))`\\n * (i.e. 0xf23a6e61, or its own function selector).\\n *\\n * @param operator The address which initiated the transfer (i.e. msg.sender)\\n * @param from The address which previously owned the token\\n * @param id The ID of the token being transferred\\n * @param value The amount of tokens being transferred\\n * @param data Additional data with no specified format\\n * @return `bytes4(keccak256(\\\"onERC1155Received(address,address,uint256,uint256,bytes)\\\"))` if transfer is allowed\\n */\\n function onERC1155Received(\\n address operator,\\n address from,\\n uint256 id,\\n uint256 value,\\n bytes calldata data\\n ) external returns (bytes4);\\n\\n /**\\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\\n * is called at the end of a `safeBatchTransferFrom` after the balances have\\n * been updated.\\n *\\n * NOTE: To accept the transfer(s), this must return\\n * `bytes4(keccak256(\\\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\\\"))`\\n * (i.e. 0xbc197c81, or its own function selector).\\n *\\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\\n * @param from The address which previously owned the token\\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\\n * @param data Additional data with no specified format\\n * @return `bytes4(keccak256(\\\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\\\"))` if transfer is allowed\\n */\\n function onERC1155BatchReceived(\\n address operator,\\n address from,\\n uint256[] calldata ids,\\n uint256[] calldata values,\\n bytes calldata data\\n ) external returns (bytes4);\\n}\\n\\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title ERC721 token receiver interface\\n * @dev Interface for any contract that wants to support safeTransfers\\n * from ERC721 asset contracts.\\n */\\ninterface IERC721Receiver {\\n /**\\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\\n * by `operator` from `from`, this function is called.\\n *\\n * It must return its Solidity selector to confirm the token transfer.\\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\\n *\\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\\n */\\n function onERC721Received(\\n address operator,\\n address from,\\n uint256 tokenId,\\n bytes calldata data\\n ) external returns (bytes4);\\n}\\n\\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\\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(\\n address(this).balance >= amount,\\n \\\"Address: insufficient balance\\\"\\n );\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(\\n success,\\n \\\"Address: unable to send value, recipient may have reverted\\\"\\n );\\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)\\n internal\\n returns (bytes memory)\\n {\\n return\\n functionCallWithValue(\\n target,\\n data,\\n 0,\\n \\\"Address: low-level call failed\\\"\\n );\\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\\n functionCallWithValue(\\n target,\\n data,\\n value,\\n \\\"Address: low-level call with value failed\\\"\\n );\\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(\\n address(this).balance >= value,\\n \\\"Address: insufficient balance for call\\\"\\n );\\n (bool success, bytes memory returndata) = target.call{value: value}(\\n data\\n );\\n return\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n internal\\n view\\n returns (bytes memory)\\n {\\n return\\n functionStaticCall(\\n target,\\n data,\\n \\\"Address: low-level static call failed\\\"\\n );\\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\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n internal\\n returns (bytes memory)\\n {\\n return\\n functionDelegateCall(\\n target,\\n data,\\n \\\"Address: low-level delegate call failed\\\"\\n );\\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\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n private\\n pure\\n {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Contract module which acts as a timelocked controller. When set as the\\n * owner of an `Ownable` smart contract, it enforces a timelock on all\\n * `onlyOwner` maintenance operations. This gives time for users of the\\n * controlled contract to exit before a potentially dangerous maintenance\\n * operation is applied.\\n *\\n * By default, this contract is self administered, meaning administration tasks\\n * have to go through the timelock process. The proposer (resp executor) role\\n * is in charge of proposing (resp executing) operations. A common use case is\\n * to position this {TimelockController} as the owner of a smart contract, with\\n * a multisig or a DAO as the sole proposer.\\n *\\n * _Available since v3.3._\\n */\\ncontract TimelockController is\\n AccessControl,\\n IERC721Receiver,\\n IERC1155Receiver\\n{\\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\\n keccak256(\\\"TIMELOCK_ADMIN_ROLE\\\");\\n bytes32 public constant PROPOSER_ROLE = keccak256(\\\"PROPOSER_ROLE\\\");\\n bytes32 public constant EXECUTOR_ROLE = keccak256(\\\"EXECUTOR_ROLE\\\");\\n bytes32 public constant CANCELLER_ROLE = keccak256(\\\"CANCELLER_ROLE\\\");\\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\\n\\n mapping(bytes32 => uint256) private _timestamps;\\n uint256 private _minDelay;\\n\\n /**\\n * @dev Emitted when a call is scheduled as part of operation `id`.\\n */\\n event CallScheduled(\\n bytes32 indexed id,\\n uint256 indexed index,\\n address target,\\n uint256 value,\\n bytes data,\\n bytes32 predecessor,\\n uint256 delay\\n );\\n\\n /**\\n * @dev Emitted when a call is performed as part of operation `id`.\\n */\\n event CallExecuted(\\n bytes32 indexed id,\\n uint256 indexed index,\\n address target,\\n uint256 value,\\n bytes data\\n );\\n\\n /**\\n * @dev Emitted when operation `id` is cancelled.\\n */\\n event Cancelled(bytes32 indexed id);\\n\\n /**\\n * @dev Emitted when the minimum delay for future operations is modified.\\n */\\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\\n\\n /**\\n * @dev Initializes the contract with the following parameters:\\n *\\n * - `minDelay`: initial minimum delay for operations\\n * - `proposers`: accounts to be granted proposer and canceller roles\\n * - `executors`: accounts to be granted executor role\\n * - `admin`: optional account to be granted admin role; disable with zero address\\n *\\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\\n * without being subject to delay, but this role should be subsequently renounced in favor of\\n * administration through timelocked proposals. Previous versions of this contract would assign\\n * this admin to the deployer automatically and should be renounced as well.\\n */\\n constructor(\\n uint256 minDelay,\\n address[] memory proposers,\\n address[] memory executors,\\n address admin\\n ) {\\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\\n\\n // self administration\\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\\n\\n // optional admin\\n if (admin != address(0)) {\\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\\n }\\n\\n // register proposers and cancellers\\n for (uint256 i = 0; i < proposers.length; ++i) {\\n _setupRole(PROPOSER_ROLE, proposers[i]);\\n _setupRole(CANCELLER_ROLE, proposers[i]);\\n }\\n\\n // register executors\\n for (uint256 i = 0; i < executors.length; ++i) {\\n _setupRole(EXECUTOR_ROLE, executors[i]);\\n }\\n\\n _minDelay = minDelay;\\n emit MinDelayChange(0, minDelay);\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only by a certain role. In\\n * addition to checking the sender's role, `address(0)` 's role is also\\n * considered. Granting a role to `address(0)` is equivalent to enabling\\n * this role for everyone.\\n */\\n modifier onlyRoleOrOpenRole(bytes32 role) {\\n if (!hasRole(role, address(0))) {\\n _checkRole(role, _msgSender());\\n }\\n _;\\n }\\n\\n /**\\n * @dev Contract might receive/hold ETH as part of the maintenance process.\\n */\\n receive() external payable {}\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override(IERC165, AccessControl)\\n returns (bool)\\n {\\n return\\n interfaceId == type(IERC1155Receiver).interfaceId ||\\n super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns whether an id correspond to a registered operation. This\\n * includes both Pending, Ready and Done operations.\\n */\\n function isOperation(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool registered)\\n {\\n return getTimestamp(id) > 0;\\n }\\n\\n /**\\n * @dev Returns whether an operation is pending or not.\\n */\\n function isOperationPending(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool pending)\\n {\\n return getTimestamp(id) > _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Returns whether an operation is ready or not.\\n */\\n function isOperationReady(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool ready)\\n {\\n uint256 timestamp = getTimestamp(id);\\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\\n }\\n\\n /**\\n * @dev Returns whether an operation is done or not.\\n */\\n function isOperationDone(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool done)\\n {\\n return getTimestamp(id) == _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Returns the timestamp at with an operation becomes ready (0 for\\n * unset operations, 1 for done operations).\\n */\\n function getTimestamp(bytes32 id)\\n public\\n view\\n virtual\\n returns (uint256 timestamp)\\n {\\n return _timestamps[id];\\n }\\n\\n /**\\n * @dev Returns the minimum delay for an operation to become valid.\\n *\\n * This value can be changed by executing an operation that calls `updateDelay`.\\n */\\n function getMinDelay() public view virtual returns (uint256 duration) {\\n return _minDelay;\\n }\\n\\n /**\\n * @dev Returns the identifier of an operation containing a single\\n * transaction.\\n */\\n function hashOperation(\\n address target,\\n uint256 value,\\n bytes calldata data,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public pure virtual returns (bytes32 hash) {\\n return keccak256(abi.encode(target, value, data, predecessor, salt));\\n }\\n\\n /**\\n * @dev Returns the identifier of an operation containing a batch of\\n * transactions.\\n */\\n function hashOperationBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public pure virtual returns (bytes32 hash) {\\n return\\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\\n }\\n\\n /**\\n * @dev Schedule an operation containing a single transaction.\\n *\\n * Emits a {CallScheduled} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'proposer' role.\\n */\\n function schedule(\\n address target,\\n uint256 value,\\n bytes calldata data,\\n bytes32 predecessor,\\n bytes32 salt,\\n uint256 delay\\n ) public virtual onlyRole(PROPOSER_ROLE) {\\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\\n _schedule(id, delay);\\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\\n }\\n\\n /**\\n * @dev Schedule an operation containing a batch of transactions.\\n *\\n * Emits one {CallScheduled} event per transaction in the batch.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'proposer' role.\\n */\\n function scheduleBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt,\\n uint256 delay\\n ) public virtual onlyRole(PROPOSER_ROLE) {\\n require(\\n targets.length == values.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n require(\\n targets.length == payloads.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n\\n bytes32 id = hashOperationBatch(\\n targets,\\n values,\\n payloads,\\n predecessor,\\n salt\\n );\\n _schedule(id, delay);\\n for (uint256 i = 0; i < targets.length; ++i) {\\n emit CallScheduled(\\n id,\\n i,\\n targets[i],\\n values[i],\\n payloads[i],\\n predecessor,\\n delay\\n );\\n }\\n }\\n\\n /**\\n * @dev Schedule an operation that is to becomes valid after a given delay.\\n */\\n function _schedule(bytes32 id, uint256 delay) private {\\n require(\\n !isOperation(id),\\n \\\"TimelockController: operation already scheduled\\\"\\n );\\n require(\\n delay >= getMinDelay(),\\n \\\"TimelockController: insufficient delay\\\"\\n );\\n _timestamps[id] = block.timestamp + delay;\\n }\\n\\n /**\\n * @dev Cancel an operation.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'canceller' role.\\n */\\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\\n require(\\n isOperationPending(id),\\n \\\"TimelockController: operation cannot be cancelled\\\"\\n );\\n delete _timestamps[id];\\n\\n emit Cancelled(id);\\n }\\n\\n /**\\n * @dev Execute an (ready) operation containing a single transaction.\\n *\\n * Emits a {CallExecuted} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'executor' role.\\n */\\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\\n // thus any modifications to the operation during reentrancy should be caught.\\n // slither-disable-next-line reentrancy-eth\\n function execute(\\n address target,\\n uint256 value,\\n bytes calldata payload,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\\n\\n _beforeCall(id, predecessor);\\n _execute(target, value, payload);\\n emit CallExecuted(id, 0, target, value, payload);\\n _afterCall(id);\\n }\\n\\n /**\\n * @dev Execute an (ready) operation containing a batch of transactions.\\n *\\n * Emits one {CallExecuted} event per transaction in the batch.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'executor' role.\\n */\\n function executeBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\\n require(\\n targets.length == values.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n require(\\n targets.length == payloads.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n\\n bytes32 id = hashOperationBatch(\\n targets,\\n values,\\n payloads,\\n predecessor,\\n salt\\n );\\n\\n _beforeCall(id, predecessor);\\n for (uint256 i = 0; i < targets.length; ++i) {\\n address target = targets[i];\\n uint256 value = values[i];\\n bytes calldata payload = payloads[i];\\n _execute(target, value, payload);\\n emit CallExecuted(id, i, target, value, payload);\\n }\\n _afterCall(id);\\n }\\n\\n /**\\n * @dev Execute an operation's call.\\n */\\n function _execute(\\n address target,\\n uint256 value,\\n bytes calldata data\\n ) internal virtual {\\n (bool success, ) = target.call{value: value}(data);\\n require(success, \\\"TimelockController: underlying transaction reverted\\\");\\n }\\n\\n /**\\n * @dev Checks before execution of an operation's calls.\\n */\\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\\n require(\\n isOperationReady(id),\\n \\\"TimelockController: operation is not ready\\\"\\n );\\n require(\\n predecessor == bytes32(0) || isOperationDone(predecessor),\\n \\\"TimelockController: missing dependency\\\"\\n );\\n }\\n\\n /**\\n * @dev Checks after execution of an operation's calls.\\n */\\n function _afterCall(bytes32 id) private {\\n require(\\n isOperationReady(id),\\n \\\"TimelockController: operation is not ready\\\"\\n );\\n _timestamps[id] = _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Changes the minimum timelock duration for future operations.\\n *\\n * Emits a {MinDelayChange} event.\\n *\\n * Requirements:\\n *\\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\\n */\\n function updateDelay(uint256 newDelay) external virtual {\\n require(\\n msg.sender == address(this),\\n \\\"TimelockController: caller must be timelock\\\"\\n );\\n emit MinDelayChange(_minDelay, newDelay);\\n _minDelay = newDelay;\\n }\\n\\n /**\\n * @dev See {IERC721Receiver-onERC721Received}.\\n */\\n function onERC721Received(\\n address,\\n address,\\n uint256,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC721Received.selector;\\n }\\n\\n /**\\n * @dev See {IERC1155Receiver-onERC1155Received}.\\n */\\n function onERC1155Received(\\n address,\\n address,\\n uint256,\\n uint256,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC1155Received.selector;\\n }\\n\\n /**\\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\\n */\\n function onERC1155BatchReceived(\\n address,\\n address,\\n uint256[] memory,\\n uint256[] memory,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC1155BatchReceived.selector;\\n }\\n}\",\"keccak256\":\"0xc3448009aeaaa7eebccd9cd969e69cb788dcbce5aa936021862c0b59197d426a\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60806040523480156200001157600080fd5b506040516200232638038062002326833981016040819052620000349162000408565b6200004f600080516020620022a6833981519152806200022d565b62000079600080516020620022c6833981519152600080516020620022a68339815191526200022d565b620000a3600080516020620022e6833981519152600080516020620022a68339815191526200022d565b620000cd60008051602062002306833981519152600080516020620022a68339815191526200022d565b620000e8600080516020620022a68339815191523062000278565b6001600160a01b03811615620001135762000113600080516020620022a68339815191528262000278565b60005b835181101562000199576200015d600080516020620022c68339815191528583815181106200014957620001496200048f565b60200260200101516200027860201b60201c565b62000186600080516020620023068339815191528583815181106200014957620001496200048f565b6200019181620004a5565b905062000116565b5060005b8251811015620001e357620001d0600080516020620022e68339815191528483815181106200014957620001496200048f565b620001db81620004a5565b90506200019d565b5060028490556040805160008152602081018690527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a150505050620004cf565b600082815260208190526040808220600101805490849055905190918391839186917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9190a4505050565b62000284828262000288565b5050565b6000828152602081815260408083206001600160a01b038516845290915290205460ff1662000284576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055620002e43390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b634e487b7160e01b600052604160045260246000fd5b80516001600160a01b03811681146200035657600080fd5b919050565b600082601f8301126200036d57600080fd5b815160206001600160401b03808311156200038c576200038c62000328565b8260051b604051601f19603f83011681018181108482111715620003b457620003b462000328565b604052938452858101830193838101925087851115620003d357600080fd5b83870191505b84821015620003fd57620003ed826200033e565b83529183019190830190620003d9565b979650505050505050565b600080600080608085870312156200041f57600080fd5b845160208601519094506001600160401b03808211156200043f57600080fd5b6200044d888389016200035b565b945060408701519150808211156200046457600080fd5b5062000473878288016200035b565b92505062000484606086016200033e565b905092959194509250565b634e487b7160e01b600052603260045260246000fd5b6000600019821415620004c857634e487b7160e01b600052601160045260246000fd5b5060010190565b611dc780620004df6000396000f3fe6080604052600436106101bb5760003560e01c80638065657f116100ec578063bc197c811161008a578063d547741f11610064578063d547741f14610582578063e38335e5146105a2578063f23a6e61146105b5578063f27a0c92146105e157600080fd5b8063bc197c8114610509578063c4d252f514610535578063d45c44351461055557600080fd5b806391d14854116100c657806391d1485414610480578063a217fddf146104a0578063b08e51c0146104b5578063b1c5f427146104e957600080fd5b80638065657f1461040c5780638f2a0bb01461042c5780638f61f4f51461044c57600080fd5b8063248a9ca31161015957806331d507501161013357806331d507501461038c57806336568abe146103ac578063584b153e146103cc57806364d62353146103ec57600080fd5b8063248a9ca31461030b5780632ab0f5291461033b5780632f2ff15d1461036c57600080fd5b80630d3cf6fc116101955780630d3cf6fc14610260578063134008d31461029457806313bc9f20146102a7578063150b7a02146102c757600080fd5b806301d5062a146101c757806301ffc9a7146101e957806307bd02651461021e57600080fd5b366101c257005b600080fd5b3480156101d357600080fd5b506101e76101e23660046113c0565b6105f6565b005b3480156101f557600080fd5b50610209610204366004611434565b61068b565b60405190151581526020015b60405180910390f35b34801561022a57600080fd5b506102527fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610215565b34801561026c57600080fd5b506102527f5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca581565b6101e76102a236600461145e565b6106b6565b3480156102b357600080fd5b506102096102c23660046114c9565b61076b565b3480156102d357600080fd5b506102f26102e2366004611597565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610215565b34801561031757600080fd5b506102526103263660046114c9565b60009081526020819052604090206001015490565b34801561034757600080fd5b506102096103563660046114c9565b6000908152600160208190526040909120541490565b34801561037857600080fd5b506101e76103873660046115fe565b610791565b34801561039857600080fd5b506102096103a73660046114c9565b6107bb565b3480156103b857600080fd5b506101e76103c73660046115fe565b6107d4565b3480156103d857600080fd5b506102096103e73660046114c9565b610857565b3480156103f857600080fd5b506101e76104073660046114c9565b61086d565b34801561041857600080fd5b5061025261042736600461145e565b610911565b34801561043857600080fd5b506101e761044736600461166e565b610950565b34801561045857600080fd5b506102527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b34801561048c57600080fd5b5061020961049b3660046115fe565b610aa2565b3480156104ac57600080fd5b50610252600081565b3480156104c157600080fd5b506102527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156104f557600080fd5b5061025261050436600461171f565b610acb565b34801561051557600080fd5b506102f2610524366004611846565b63bc197c8160e01b95945050505050565b34801561054157600080fd5b506101e76105503660046114c9565b610b10565b34801561056157600080fd5b506102526105703660046114c9565b60009081526001602052604090205490565b34801561058e57600080fd5b506101e761059d3660046115fe565b610be5565b6101e76105b036600461171f565b610c0a565b3480156105c157600080fd5b506102f26105d03660046118ef565b63f23a6e6160e01b95945050505050565b3480156105ed57600080fd5b50600254610252565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161062081610d94565b6000610630898989898989610911565b905061063c8184610da1565b6000817f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8b8b8b8b8b8a6040516106789695949392919061197c565b60405180910390a3505050505050505050565b60006001600160e01b03198216630271189760e51b14806106b057506106b082610e90565b92915050565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e636106e2816000610aa2565b6106f0576106f08133610ec5565b6000610700888888888888610911565b905061070c8185610f1e565b61071888888888610fba565b6000817fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b588a8a8a8a60405161075094939291906119b9565b60405180910390a36107618161108d565b5050505050505050565b60008181526001602052604081205460018111801561078a5750428111155b9392505050565b6000828152602081905260409020600101546107ac81610d94565b6107b683836110c6565b505050565b60008181526001602052604081205481905b1192915050565b6001600160a01b03811633146108495760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b610853828261114a565b5050565b60008181526001602081905260408220546107cd565b3330146108d05760405162461bcd60e51b815260206004820152602b60248201527f54696d656c6f636b436f6e74726f6c6c65723a2063616c6c6572206d7573742060448201526a62652074696d656c6f636b60a81b6064820152608401610840565b60025460408051918252602082018390527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a1600255565b600086868686868660405160200161092e9695949392919061197c565b6040516020818303038152906040528051906020012090509695505050505050565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161097a81610d94565b8887146109995760405162461bcd60e51b8152600401610840906119eb565b8885146109b85760405162461bcd60e51b8152600401610840906119eb565b60006109ca8b8b8b8b8b8b8b8b610acb565b90506109d68184610da1565b60005b8a811015610a945780827f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8e8e85818110610a1657610a16611a2e565b9050602002016020810190610a2b9190611a44565b8d8d86818110610a3d57610a3d611a2e565b905060200201358c8c87818110610a5657610a56611a2e565b9050602002810190610a689190611a5f565b8c8b604051610a7c9695949392919061197c565b60405180910390a3610a8d81611abb565b90506109d9565b505050505050505050505050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60008888888888888888604051602001610aec989796959493929190611b66565b60405160208183030381529060405280519060200120905098975050505050505050565b7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783610b3a81610d94565b610b4382610857565b610ba95760405162461bcd60e51b815260206004820152603160248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e2063616044820152701b9b9bdd0818994818d85b98d95b1b1959607a1b6064820152608401610840565b6000828152600160205260408082208290555183917fbaa1eb22f2a492ba1a5fea61b8df4d27c6c8b5f3971e63bb58fa14ff72eedb7091a25050565b600082815260208190526040902060010154610c0081610d94565b6107b6838361114a565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63610c36816000610aa2565b610c4457610c448133610ec5565b878614610c635760405162461bcd60e51b8152600401610840906119eb565b878414610c825760405162461bcd60e51b8152600401610840906119eb565b6000610c948a8a8a8a8a8a8a8a610acb565b9050610ca08185610f1e565b60005b89811015610d7e5760008b8b83818110610cbf57610cbf611a2e565b9050602002016020810190610cd49190611a44565b905060008a8a84818110610cea57610cea611a2e565b9050602002013590503660008a8a86818110610d0857610d08611a2e565b9050602002810190610d1a9190611a5f565b91509150610d2a84848484610fba565b84867fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b5886868686604051610d6194939291906119b9565b60405180910390a35050505080610d7790611abb565b9050610ca3565b50610d888161108d565b50505050505050505050565b610d9e8133610ec5565b50565b610daa826107bb565b15610e0f5760405162461bcd60e51b815260206004820152602f60248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e20616c60448201526e1c9958591e481cd8da19591d5b1959608a1b6064820152608401610840565b600254811015610e705760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a20696e73756666696369656e746044820152652064656c617960d01b6064820152608401610840565b610e7a8142611c11565b6000928352600160205260409092209190915550565b60006001600160e01b03198216637965db0b60e01b14806106b057506301ffc9a760e01b6001600160e01b03198316146106b0565b610ecf8282610aa2565b61085357610edc816111af565b610ee78360206111c1565b604051602001610ef8929190611c59565b60408051601f198184030181529082905262461bcd60e51b825261084091600401611cce565b610f278261076b565b610f435760405162461bcd60e51b815260040161084090611d01565b801580610f5f5750600081815260016020819052604090912054145b6108535760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a206d697373696e6720646570656044820152656e64656e637960d01b6064820152608401610840565b6000846001600160a01b0316848484604051610fd7929190611d4b565b60006040518083038185875af1925050503d8060008114611014576040519150601f19603f3d011682016040523d82523d6000602084013e611019565b606091505b50509050806110865760405162461bcd60e51b815260206004820152603360248201527f54696d656c6f636b436f6e74726f6c6c65723a20756e6465726c79696e6720746044820152721c985b9cd858dd1a5bdb881c995d995c9d1959606a1b6064820152608401610840565b5050505050565b6110968161076b565b6110b25760405162461bcd60e51b815260040161084090611d01565b600090815260016020819052604090912055565b6110d08282610aa2565b610853576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556111063390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6111548282610aa2565b15610853576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60606106b06001600160a01b03831660145b606060006111d0836002611d5b565b6111db906002611c11565b6001600160401b038111156111f2576111f26114e2565b6040519080825280601f01601f19166020018201604052801561121c576020820181803683370190505b509050600360fc1b8160008151811061123757611237611a2e565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061126657611266611a2e565b60200101906001600160f81b031916908160001a905350600061128a846002611d5b565b611295906001611c11565b90505b600181111561130d576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106112c9576112c9611a2e565b1a60f81b8282815181106112df576112df611a2e565b60200101906001600160f81b031916908160001a90535060049490941c9361130681611d7a565b9050611298565b50831561078a5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610840565b80356001600160a01b038116811461137357600080fd5b919050565b60008083601f84011261138a57600080fd5b5081356001600160401b038111156113a157600080fd5b6020830191508360208285010111156113b957600080fd5b9250929050565b600080600080600080600060c0888a0312156113db57600080fd5b6113e48861135c565b96506020880135955060408801356001600160401b0381111561140657600080fd5b6114128a828b01611378565b989b979a50986060810135976080820135975060a09091013595509350505050565b60006020828403121561144657600080fd5b81356001600160e01b03198116811461078a57600080fd5b60008060008060008060a0878903121561147757600080fd5b6114808761135c565b95506020870135945060408701356001600160401b038111156114a257600080fd5b6114ae89828a01611378565b979a9699509760608101359660809091013595509350505050565b6000602082840312156114db57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715611520576115206114e2565b604052919050565b600082601f83011261153957600080fd5b81356001600160401b03811115611552576115526114e2565b611565601f8201601f19166020016114f8565b81815284602083860101111561157a57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156115ad57600080fd5b6115b68561135c565b93506115c46020860161135c565b92506040850135915060608501356001600160401b038111156115e657600080fd5b6115f287828801611528565b91505092959194509250565b6000806040838503121561161157600080fd5b823591506116216020840161135c565b90509250929050565b60008083601f84011261163c57600080fd5b5081356001600160401b0381111561165357600080fd5b6020830191508360208260051b85010111156113b957600080fd5b600080600080600080600080600060c08a8c03121561168c57600080fd5b89356001600160401b03808211156116a357600080fd5b6116af8d838e0161162a565b909b50995060208c01359150808211156116c857600080fd5b6116d48d838e0161162a565b909950975060408c01359150808211156116ed57600080fd5b506116fa8c828d0161162a565b9a9d999c50979a969997986060880135976080810135975060a0013595509350505050565b60008060008060008060008060a0898b03121561173b57600080fd5b88356001600160401b038082111561175257600080fd5b61175e8c838d0161162a565b909a50985060208b013591508082111561177757600080fd5b6117838c838d0161162a565b909850965060408b013591508082111561179c57600080fd5b506117a98b828c0161162a565b999c989b509699959896976060870135966080013595509350505050565b600082601f8301126117d857600080fd5b813560206001600160401b038211156117f3576117f36114e2565b8160051b6118028282016114f8565b928352848101820192828101908785111561181c57600080fd5b83870192505b8483101561183b57823582529183019190830190611822565b979650505050505050565b600080600080600060a0868803121561185e57600080fd5b6118678661135c565b94506118756020870161135c565b935060408601356001600160401b038082111561189157600080fd5b61189d89838a016117c7565b945060608801359150808211156118b357600080fd5b6118bf89838a016117c7565b935060808801359150808211156118d557600080fd5b506118e288828901611528565b9150509295509295909350565b600080600080600060a0868803121561190757600080fd5b6119108661135c565b945061191e6020870161135c565b9350604086013592506060860135915060808601356001600160401b0381111561194757600080fd5b6118e288828901611528565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60018060a01b038716815285602082015260a0604082015260006119a460a083018688611953565b60608301949094525060800152949350505050565b60018060a01b03851681528360208201526060604082015260006119e1606083018486611953565b9695505050505050565b60208082526023908201527f54696d656c6f636b436f6e74726f6c6c65723a206c656e677468206d69736d616040820152620e8c6d60eb1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215611a5657600080fd5b61078a8261135c565b6000808335601e19843603018112611a7657600080fd5b8301803591506001600160401b03821115611a9057600080fd5b6020019150368190038213156113b957600080fd5b634e487b7160e01b600052601160045260246000fd5b6000600019821415611acf57611acf611aa5565b5060010190565b81835260006020808501808196508560051b810191508460005b87811015611b595782840389528135601e19883603018112611b1157600080fd5b870180356001600160401b03811115611b2957600080fd5b803603891315611b3857600080fd5b611b458682898501611953565b9a87019a9550505090840190600101611af0565b5091979650505050505050565b60a0808252810188905260008960c08301825b8b811015611ba7576001600160a01b03611b928461135c565b16825260209283019290910190600101611b79565b5083810360208501528881526001600160fb1b03891115611bc757600080fd5b8860051b9150818a602083013781810191505060208101600081526020848303016040850152611bf881888a611ad6565b6060850196909652505050608001529695505050505050565b60008219821115611c2457611c24611aa5565b500190565b60005b83811015611c44578181015183820152602001611c2c565b83811115611c53576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c91816017850160208801611c29565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611cc2816028840160208801611c29565b01602801949350505050565b6020815260008251806020840152611ced816040850160208701611c29565b601f01601f19169190910160400192915050565b6020808252602a908201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e206973604082015269206e6f7420726561647960b01b606082015260800190565b8183823760009101908152919050565b6000816000190483118215151615611d7557611d75611aa5565b500290565b600081611d8957611d89611aa5565b50600019019056fea2646970667358221220dca2012434ae0ee932ca779f9ca2670c90f60d6e9240e5d6e19d5d2d78265ff464736f6c634300080b00335f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5b09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1d8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63fd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "deployedBytecode": "0x6080604052600436106101bb5760003560e01c80638065657f116100ec578063bc197c811161008a578063d547741f11610064578063d547741f14610582578063e38335e5146105a2578063f23a6e61146105b5578063f27a0c92146105e157600080fd5b8063bc197c8114610509578063c4d252f514610535578063d45c44351461055557600080fd5b806391d14854116100c657806391d1485414610480578063a217fddf146104a0578063b08e51c0146104b5578063b1c5f427146104e957600080fd5b80638065657f1461040c5780638f2a0bb01461042c5780638f61f4f51461044c57600080fd5b8063248a9ca31161015957806331d507501161013357806331d507501461038c57806336568abe146103ac578063584b153e146103cc57806364d62353146103ec57600080fd5b8063248a9ca31461030b5780632ab0f5291461033b5780632f2ff15d1461036c57600080fd5b80630d3cf6fc116101955780630d3cf6fc14610260578063134008d31461029457806313bc9f20146102a7578063150b7a02146102c757600080fd5b806301d5062a146101c757806301ffc9a7146101e957806307bd02651461021e57600080fd5b366101c257005b600080fd5b3480156101d357600080fd5b506101e76101e23660046113c0565b6105f6565b005b3480156101f557600080fd5b50610209610204366004611434565b61068b565b60405190151581526020015b60405180910390f35b34801561022a57600080fd5b506102527fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610215565b34801561026c57600080fd5b506102527f5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca581565b6101e76102a236600461145e565b6106b6565b3480156102b357600080fd5b506102096102c23660046114c9565b61076b565b3480156102d357600080fd5b506102f26102e2366004611597565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610215565b34801561031757600080fd5b506102526103263660046114c9565b60009081526020819052604090206001015490565b34801561034757600080fd5b506102096103563660046114c9565b6000908152600160208190526040909120541490565b34801561037857600080fd5b506101e76103873660046115fe565b610791565b34801561039857600080fd5b506102096103a73660046114c9565b6107bb565b3480156103b857600080fd5b506101e76103c73660046115fe565b6107d4565b3480156103d857600080fd5b506102096103e73660046114c9565b610857565b3480156103f857600080fd5b506101e76104073660046114c9565b61086d565b34801561041857600080fd5b5061025261042736600461145e565b610911565b34801561043857600080fd5b506101e761044736600461166e565b610950565b34801561045857600080fd5b506102527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b34801561048c57600080fd5b5061020961049b3660046115fe565b610aa2565b3480156104ac57600080fd5b50610252600081565b3480156104c157600080fd5b506102527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156104f557600080fd5b5061025261050436600461171f565b610acb565b34801561051557600080fd5b506102f2610524366004611846565b63bc197c8160e01b95945050505050565b34801561054157600080fd5b506101e76105503660046114c9565b610b10565b34801561056157600080fd5b506102526105703660046114c9565b60009081526001602052604090205490565b34801561058e57600080fd5b506101e761059d3660046115fe565b610be5565b6101e76105b036600461171f565b610c0a565b3480156105c157600080fd5b506102f26105d03660046118ef565b63f23a6e6160e01b95945050505050565b3480156105ed57600080fd5b50600254610252565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161062081610d94565b6000610630898989898989610911565b905061063c8184610da1565b6000817f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8b8b8b8b8b8a6040516106789695949392919061197c565b60405180910390a3505050505050505050565b60006001600160e01b03198216630271189760e51b14806106b057506106b082610e90565b92915050565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e636106e2816000610aa2565b6106f0576106f08133610ec5565b6000610700888888888888610911565b905061070c8185610f1e565b61071888888888610fba565b6000817fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b588a8a8a8a60405161075094939291906119b9565b60405180910390a36107618161108d565b5050505050505050565b60008181526001602052604081205460018111801561078a5750428111155b9392505050565b6000828152602081905260409020600101546107ac81610d94565b6107b683836110c6565b505050565b60008181526001602052604081205481905b1192915050565b6001600160a01b03811633146108495760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b610853828261114a565b5050565b60008181526001602081905260408220546107cd565b3330146108d05760405162461bcd60e51b815260206004820152602b60248201527f54696d656c6f636b436f6e74726f6c6c65723a2063616c6c6572206d7573742060448201526a62652074696d656c6f636b60a81b6064820152608401610840565b60025460408051918252602082018390527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a1600255565b600086868686868660405160200161092e9695949392919061197c565b6040516020818303038152906040528051906020012090509695505050505050565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161097a81610d94565b8887146109995760405162461bcd60e51b8152600401610840906119eb565b8885146109b85760405162461bcd60e51b8152600401610840906119eb565b60006109ca8b8b8b8b8b8b8b8b610acb565b90506109d68184610da1565b60005b8a811015610a945780827f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8e8e85818110610a1657610a16611a2e565b9050602002016020810190610a2b9190611a44565b8d8d86818110610a3d57610a3d611a2e565b905060200201358c8c87818110610a5657610a56611a2e565b9050602002810190610a689190611a5f565b8c8b604051610a7c9695949392919061197c565b60405180910390a3610a8d81611abb565b90506109d9565b505050505050505050505050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60008888888888888888604051602001610aec989796959493929190611b66565b60405160208183030381529060405280519060200120905098975050505050505050565b7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783610b3a81610d94565b610b4382610857565b610ba95760405162461bcd60e51b815260206004820152603160248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e2063616044820152701b9b9bdd0818994818d85b98d95b1b1959607a1b6064820152608401610840565b6000828152600160205260408082208290555183917fbaa1eb22f2a492ba1a5fea61b8df4d27c6c8b5f3971e63bb58fa14ff72eedb7091a25050565b600082815260208190526040902060010154610c0081610d94565b6107b6838361114a565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63610c36816000610aa2565b610c4457610c448133610ec5565b878614610c635760405162461bcd60e51b8152600401610840906119eb565b878414610c825760405162461bcd60e51b8152600401610840906119eb565b6000610c948a8a8a8a8a8a8a8a610acb565b9050610ca08185610f1e565b60005b89811015610d7e5760008b8b83818110610cbf57610cbf611a2e565b9050602002016020810190610cd49190611a44565b905060008a8a84818110610cea57610cea611a2e565b9050602002013590503660008a8a86818110610d0857610d08611a2e565b9050602002810190610d1a9190611a5f565b91509150610d2a84848484610fba565b84867fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b5886868686604051610d6194939291906119b9565b60405180910390a35050505080610d7790611abb565b9050610ca3565b50610d888161108d565b50505050505050505050565b610d9e8133610ec5565b50565b610daa826107bb565b15610e0f5760405162461bcd60e51b815260206004820152602f60248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e20616c60448201526e1c9958591e481cd8da19591d5b1959608a1b6064820152608401610840565b600254811015610e705760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a20696e73756666696369656e746044820152652064656c617960d01b6064820152608401610840565b610e7a8142611c11565b6000928352600160205260409092209190915550565b60006001600160e01b03198216637965db0b60e01b14806106b057506301ffc9a760e01b6001600160e01b03198316146106b0565b610ecf8282610aa2565b61085357610edc816111af565b610ee78360206111c1565b604051602001610ef8929190611c59565b60408051601f198184030181529082905262461bcd60e51b825261084091600401611cce565b610f278261076b565b610f435760405162461bcd60e51b815260040161084090611d01565b801580610f5f5750600081815260016020819052604090912054145b6108535760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a206d697373696e6720646570656044820152656e64656e637960d01b6064820152608401610840565b6000846001600160a01b0316848484604051610fd7929190611d4b565b60006040518083038185875af1925050503d8060008114611014576040519150601f19603f3d011682016040523d82523d6000602084013e611019565b606091505b50509050806110865760405162461bcd60e51b815260206004820152603360248201527f54696d656c6f636b436f6e74726f6c6c65723a20756e6465726c79696e6720746044820152721c985b9cd858dd1a5bdb881c995d995c9d1959606a1b6064820152608401610840565b5050505050565b6110968161076b565b6110b25760405162461bcd60e51b815260040161084090611d01565b600090815260016020819052604090912055565b6110d08282610aa2565b610853576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556111063390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6111548282610aa2565b15610853576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60606106b06001600160a01b03831660145b606060006111d0836002611d5b565b6111db906002611c11565b6001600160401b038111156111f2576111f26114e2565b6040519080825280601f01601f19166020018201604052801561121c576020820181803683370190505b509050600360fc1b8160008151811061123757611237611a2e565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061126657611266611a2e565b60200101906001600160f81b031916908160001a905350600061128a846002611d5b565b611295906001611c11565b90505b600181111561130d576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106112c9576112c9611a2e565b1a60f81b8282815181106112df576112df611a2e565b60200101906001600160f81b031916908160001a90535060049490941c9361130681611d7a565b9050611298565b50831561078a5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610840565b80356001600160a01b038116811461137357600080fd5b919050565b60008083601f84011261138a57600080fd5b5081356001600160401b038111156113a157600080fd5b6020830191508360208285010111156113b957600080fd5b9250929050565b600080600080600080600060c0888a0312156113db57600080fd5b6113e48861135c565b96506020880135955060408801356001600160401b0381111561140657600080fd5b6114128a828b01611378565b989b979a50986060810135976080820135975060a09091013595509350505050565b60006020828403121561144657600080fd5b81356001600160e01b03198116811461078a57600080fd5b60008060008060008060a0878903121561147757600080fd5b6114808761135c565b95506020870135945060408701356001600160401b038111156114a257600080fd5b6114ae89828a01611378565b979a9699509760608101359660809091013595509350505050565b6000602082840312156114db57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715611520576115206114e2565b604052919050565b600082601f83011261153957600080fd5b81356001600160401b03811115611552576115526114e2565b611565601f8201601f19166020016114f8565b81815284602083860101111561157a57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156115ad57600080fd5b6115b68561135c565b93506115c46020860161135c565b92506040850135915060608501356001600160401b038111156115e657600080fd5b6115f287828801611528565b91505092959194509250565b6000806040838503121561161157600080fd5b823591506116216020840161135c565b90509250929050565b60008083601f84011261163c57600080fd5b5081356001600160401b0381111561165357600080fd5b6020830191508360208260051b85010111156113b957600080fd5b600080600080600080600080600060c08a8c03121561168c57600080fd5b89356001600160401b03808211156116a357600080fd5b6116af8d838e0161162a565b909b50995060208c01359150808211156116c857600080fd5b6116d48d838e0161162a565b909950975060408c01359150808211156116ed57600080fd5b506116fa8c828d0161162a565b9a9d999c50979a969997986060880135976080810135975060a0013595509350505050565b60008060008060008060008060a0898b03121561173b57600080fd5b88356001600160401b038082111561175257600080fd5b61175e8c838d0161162a565b909a50985060208b013591508082111561177757600080fd5b6117838c838d0161162a565b909850965060408b013591508082111561179c57600080fd5b506117a98b828c0161162a565b999c989b509699959896976060870135966080013595509350505050565b600082601f8301126117d857600080fd5b813560206001600160401b038211156117f3576117f36114e2565b8160051b6118028282016114f8565b928352848101820192828101908785111561181c57600080fd5b83870192505b8483101561183b57823582529183019190830190611822565b979650505050505050565b600080600080600060a0868803121561185e57600080fd5b6118678661135c565b94506118756020870161135c565b935060408601356001600160401b038082111561189157600080fd5b61189d89838a016117c7565b945060608801359150808211156118b357600080fd5b6118bf89838a016117c7565b935060808801359150808211156118d557600080fd5b506118e288828901611528565b9150509295509295909350565b600080600080600060a0868803121561190757600080fd5b6119108661135c565b945061191e6020870161135c565b9350604086013592506060860135915060808601356001600160401b0381111561194757600080fd5b6118e288828901611528565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60018060a01b038716815285602082015260a0604082015260006119a460a083018688611953565b60608301949094525060800152949350505050565b60018060a01b03851681528360208201526060604082015260006119e1606083018486611953565b9695505050505050565b60208082526023908201527f54696d656c6f636b436f6e74726f6c6c65723a206c656e677468206d69736d616040820152620e8c6d60eb1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215611a5657600080fd5b61078a8261135c565b6000808335601e19843603018112611a7657600080fd5b8301803591506001600160401b03821115611a9057600080fd5b6020019150368190038213156113b957600080fd5b634e487b7160e01b600052601160045260246000fd5b6000600019821415611acf57611acf611aa5565b5060010190565b81835260006020808501808196508560051b810191508460005b87811015611b595782840389528135601e19883603018112611b1157600080fd5b870180356001600160401b03811115611b2957600080fd5b803603891315611b3857600080fd5b611b458682898501611953565b9a87019a9550505090840190600101611af0565b5091979650505050505050565b60a0808252810188905260008960c08301825b8b811015611ba7576001600160a01b03611b928461135c565b16825260209283019290910190600101611b79565b5083810360208501528881526001600160fb1b03891115611bc757600080fd5b8860051b9150818a602083013781810191505060208101600081526020848303016040850152611bf881888a611ad6565b6060850196909652505050608001529695505050505050565b60008219821115611c2457611c24611aa5565b500190565b60005b83811015611c44578181015183820152602001611c2c565b83811115611c53576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c91816017850160208801611c29565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611cc2816028840160208801611c29565b01602801949350505050565b6020815260008251806020840152611ced816040850160208701611c29565b601f01601f19169190910160400192915050565b6020808252602a908201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e206973604082015269206e6f7420726561647960b01b606082015260800190565b8183823760009101908152919050565b6000816000190483118215151615611d7557611d75611aa5565b500290565b600081611d8957611d89611aa5565b50600019019056fea2646970667358221220dca2012434ae0ee932ca779f9ca2670c90f60d6e9240e5d6e19d5d2d78265ff464736f6c634300080b0033", + "devdoc": { + "details": "Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied. By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer. _Available since v3.3._", + "events": { + "CallExecuted(bytes32,uint256,address,uint256,bytes)": { + "details": "Emitted when a call is performed as part of operation `id`." + }, + "CallScheduled(bytes32,uint256,address,uint256,bytes,bytes32,uint256)": { + "details": "Emitted when a call is scheduled as part of operation `id`." + }, + "Cancelled(bytes32)": { + "details": "Emitted when operation `id` is cancelled." + }, + "MinDelayChange(uint256,uint256)": { + "details": "Emitted when the minimum delay for future operations is modified." + } + }, + "kind": "dev", + "methods": { + "cancel(bytes32)": { + "details": "Cancel an operation. Requirements: - the caller must have the 'canceller' role." + }, + "constructor": { + "details": "Initializes the contract with the following parameters: - `minDelay`: initial minimum delay for operations - `proposers`: accounts to be granted proposer and canceller roles - `executors`: accounts to be granted executor role - `admin`: optional account to be granted admin role; disable with zero address IMPORTANT: The optional admin can aid with initial configuration of roles after deployment without being subject to delay, but this role should be subsequently renounced in favor of administration through timelocked proposals. Previous versions of this contract would assign this admin to the deployer automatically and should be renounced as well." + }, + "execute(address,uint256,bytes,bytes32,bytes32)": { + "details": "Execute an (ready) operation containing a single transaction. Emits a {CallExecuted} event. Requirements: - the caller must have the 'executor' role." + }, + "executeBatch(address[],uint256[],bytes[],bytes32,bytes32)": { + "details": "Execute an (ready) operation containing a batch of transactions. Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' role." + }, + "getMinDelay()": { + "details": "Returns the minimum delay for an operation to become valid. This value can be changed by executing an operation that calls `updateDelay`." + }, + "getRoleAdmin(bytes32)": { + "details": "Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}." + }, + "getTimestamp(bytes32)": { + "details": "Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations)." + }, + "grantRole(bytes32,address)": { + "details": "Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event." + }, + "hasRole(bytes32,address)": { + "details": "Returns `true` if `account` has been granted `role`." + }, + "hashOperation(address,uint256,bytes,bytes32,bytes32)": { + "details": "Returns the identifier of an operation containing a single transaction." + }, + "hashOperationBatch(address[],uint256[],bytes[],bytes32,bytes32)": { + "details": "Returns the identifier of an operation containing a batch of transactions." + }, + "isOperation(bytes32)": { + "details": "Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations." + }, + "isOperationDone(bytes32)": { + "details": "Returns whether an operation is done or not." + }, + "isOperationPending(bytes32)": { + "details": "Returns whether an operation is pending or not." + }, + "isOperationReady(bytes32)": { + "details": "Returns whether an operation is ready or not." + }, + "onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)": { + "details": "See {IERC1155Receiver-onERC1155BatchReceived}." + }, + "onERC1155Received(address,address,uint256,uint256,bytes)": { + "details": "See {IERC1155Receiver-onERC1155Received}." + }, + "onERC721Received(address,address,uint256,bytes)": { + "details": "See {IERC721Receiver-onERC721Received}." + }, + "renounceRole(bytes32,address)": { + "details": "Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event." + }, + "revokeRole(bytes32,address)": { + "details": "Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event." + }, + "schedule(address,uint256,bytes,bytes32,bytes32,uint256)": { + "details": "Schedule an operation containing a single transaction. Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role." + }, + "scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256)": { + "details": "Schedule an operation containing a batch of transactions. Emits one {CallScheduled} event per transaction in the batch. Requirements: - the caller must have the 'proposer' role." + }, + "supportsInterface(bytes4)": { + "details": "See {IERC165-supportsInterface}." + }, + "updateDelay(uint256)": { + "details": "Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 45983, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_roles", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(RoleData)45978_storage)" + }, + { + "astId": 46697, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_timestamps", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_bytes32,t_uint256)" + }, + { + "astId": 46699, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_minDelay", + "offset": 0, + "slot": "2", + "type": "t_uint256" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => bool)", + "numberOfBytes": "32", + "value": "t_bool" + }, + "t_mapping(t_bytes32,t_struct(RoleData)45978_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct AccessControl.RoleData)", + "numberOfBytes": "32", + "value": "t_struct(RoleData)45978_storage" + }, + "t_mapping(t_bytes32,t_uint256)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_struct(RoleData)45978_storage": { + "encoding": "inplace", + "label": "struct AccessControl.RoleData", + "members": [ + { + "astId": 45975, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "members", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_bool)" + }, + { + "astId": 45977, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "adminRole", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/UniswapPricingHelper.json b/packages/contracts/deployments/bsc/UniswapPricingHelper.json new file mode 100644 index 000000000..22c5513ae --- /dev/null +++ b/packages/contracts/deployments/bsc/UniswapPricingHelper.json @@ -0,0 +1,133 @@ +{ + "address": "0x8AAdB10450dc7E9814AB77bdAD8A96f006AEBff0", + "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": "0x115128433d725be629e13738c3658665e2c9cab92edbda4d7cdaa13c7cbfbb55", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x8AAdB10450dc7E9814AB77bdAD8A96f006AEBff0", + "transactionIndex": 36, + "gasUsed": "923820", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xa931d866fc75af02645ee96f13203c84dee2e0bb2919c06580ce173881528729", + "transactionHash": "0x115128433d725be629e13738c3658665e2c9cab92edbda4d7cdaa13c7cbfbb55", + "logs": [], + "blockNumber": 81088732, + "cumulativeGasUsed": "7826792", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/price_oracles/UniswapPricingHelper.sol\":\"UniswapPricingHelper\"},\"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/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\"},\"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/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\"},\"contracts/price_oracles/UniswapPricingHelper.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\n\\n//import \\\"forge-std/console.sol\\\";\\n \\n\\nimport {IUniswapPricingLibrary} from \\\"../interfaces/IUniswapPricingLibrary.sol\\\";\\n\\n \\n \\n// Libraries \\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 \\n*/\\n\\ncontract UniswapPricingHelper\\n{\\n\\n\\n // use uniswap exp helper instead ? \\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\\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x5588c1215275d954f5c2a4602844b78a67794780936fff363c749721cb1a8e49\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b50610fc1806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80633bbe42751461003b578063a1a73faf14610060575b600080fd5b61004e610049366004610aec565b610073565b60405190815260200160405180910390f35b61004e61006e366004610b8b565b61015d565b60006002825111156100cc5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101325760006100fb836000815181106100ee576100ee610ba7565b602002602001015161015d565b90506000610115846001815181106100ee576100ee610ba7565b905061012a8282670de0b6b3a764000061018e565b949350505050565b81516001141561015857610152826000815181106100ee576100ee610ba7565b92915050565b919050565b6000806101728360000151846040015161030a565b60208401519091501561012a82670de0b6b3a7640000836104e1565b6000808060001985870985870292508281108382030391505080600014156101c857600084116101bd57600080fd5b508290049050610303565b8084116101d457600080fd5b6000848688098084039381119092039190506000856101f581196001610bd3565b169586900495938490049360008190030460010190506102158184610beb565b909317926000610226876003610beb565b60021890506102358188610beb565b610240906002610c0a565b61024a9082610beb565b90506102568188610beb565b610261906002610c0a565b61026b9082610beb565b90506102778188610beb565b610282906002610c0a565b61028c9082610beb565b90506102988188610beb565b6102a3906002610c0a565b6102ad9082610beb565b90506102b98188610beb565b6102c4906002610c0a565b6102ce9082610beb565b90506102da8188610beb565b6102e5906002610c0a565b6102ef9082610beb565b90506102fb8186610beb565b955050505050505b9392505050565b600063ffffffff821661038857826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610355573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103799190610c33565b50949550610152945050505050565b6040805160028082526060820183526000926020830190803683370190505090506103b4836001610cd2565b816000815181106103c7576103c7610ba7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106103f6576103f6610ba7565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd9061043a908590600401610cfa565b600060405180830381865afa158015610457573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261047f9190810190610db3565b5090506104d88460030b8260008151811061049c5761049c610ba7565b6020026020010151836001815181106104b7576104b7610ba7565b60200260200101516104c99190610e7f565b6104d39190610ee5565b6105b0565b95945050505050565b60006001600160801b036001600160a01b0385161161055457600061050f6001600160a01b03861680610beb565b905082156105345761052f600160c01b856001600160801b03168361018e565b61054c565b61054c81856001600160801b0316600160c01b61018e565b915050610303565b60006105736001600160a01b038616806801000000000000000061018e565b9050821561059857610593600160801b856001600160801b03168361018e565b6104d8565b6104d881856001600160801b0316600160801b61018e565b60008060008360020b126105c7578260020b6105d4565b8260020b6105d490610f23565b90506105e3620d89e719610f40565b62ffffff1681111561061b5760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064016100c3565b60006001821661062f57600160801b610641565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561068057608061067b826ffff97272373d413259a46990580e213a610beb565b901c90505b60048216156106aa5760806106a5826ffff2e50f5f656932ef12357cf3c7fdcc610beb565b901c90505b60088216156106d45760806106cf826fffe5caca7e10e4e61c3624eaa0941cd0610beb565b901c90505b60108216156106fe5760806106f9826fffcb9843d60f6159c9db58835c926644610beb565b901c90505b6020821615610728576080610723826fff973b41fa98c081472e6896dfb254c0610beb565b901c90505b604082161561075257608061074d826fff2ea16466c96a3843ec78b326b52861610beb565b901c90505b608082161561077c576080610777826ffe5dee046a99a2a811c461f1969c3053610beb565b901c90505b6101008216156107a75760806107a2826ffcbe86c7900a88aedcffc83b479aa3a4610beb565b901c90505b6102008216156107d25760806107cd826ff987a7253ac413176f2b074cf7815e54610beb565b901c90505b6104008216156107fd5760806107f8826ff3392b0822b70005940c7a398e4b70f3610beb565b901c90505b610800821615610828576080610823826fe7159475a2c29b7443b29c7fa6e889d9610beb565b901c90505b61100082161561085357608061084e826fd097f3bdfd2022b8845ad8f792aa5825610beb565b901c90505b61200082161561087e576080610879826fa9f746462d870fdf8a65dc1f90e061e5610beb565b901c90505b6140008216156108a95760806108a4826f70d869a156d2a1b890bb3df62baf32f7610beb565b901c90505b6180008216156108d45760806108cf826f31be135f97d08fd981231505542fcfa6610beb565b901c90505b620100008216156109005760806108fb826f09aa508b5b7a84e1c677de54f3e99bc9610beb565b901c90505b6202000082161561092b576080610926826e5d6af8dedb81196699c329225ee604610beb565b901c90505b62040000821615610955576080610950826d2216e584f5fa1ea926041bedfe98610beb565b901c90505b6208000082161561097d576080610978826b048a170391f7dc42444e8fa2610beb565b901c90505b60008460020b13156109985761099581600019610f63565b90505b6109a764010000000082610f77565b156109b35760016109b6565b60005b61012a9060ff16602083901c610bd3565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a0657610a066109c7565b604052919050565b600067ffffffffffffffff821115610a2857610a286109c7565b5060051b60200190565b6001600160a01b0381168114610a4757600080fd5b50565b8015158114610a4757600080fd5b600060a08284031215610a6a57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a8d57610a8d6109c7565b6040529050808235610a9e81610a32565b81526020830135610aae81610a4a565b6020820152604083013563ffffffff81168114610aca57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b60006020808385031215610aff57600080fd5b823567ffffffffffffffff811115610b1657600080fd5b8301601f81018513610b2757600080fd5b8035610b3a610b3582610a0e565b6109dd565b81815260a09182028301840191848201919088841115610b5957600080fd5b938501935b83851015610b7f57610b708986610a58565b83529384019391850191610b5e565b50979650505050505050565b600060a08284031215610b9d57600080fd5b6103038383610a58565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60008219821115610be657610be6610bbd565b500190565b6000816000190483118215151615610c0557610c05610bbd565b500290565b600082821015610c1c57610c1c610bbd565b500390565b805161ffff8116811461015857600080fd5b600080600080600080600060e0888a031215610c4e57600080fd5b8751610c5981610a32565b8097505060208801518060020b8114610c7157600080fd5b9550610c7f60408901610c21565b9450610c8d60608901610c21565b9350610c9b60808901610c21565b925060a088015160ff81168114610cb157600080fd5b60c0890151909250610cc281610a4a565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610cf157610cf1610bbd565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610d3857835163ffffffff1683529284019291840191600101610d16565b50909695505050505050565b600082601f830112610d5557600080fd5b81516020610d65610b3583610a0e565b82815260059290921b84018101918181019086841115610d8457600080fd5b8286015b84811015610da8578051610d9b81610a32565b8352918301918301610d88565b509695505050505050565b60008060408385031215610dc657600080fd5b825167ffffffffffffffff80821115610dde57600080fd5b818501915085601f830112610df257600080fd5b81516020610e02610b3583610a0e565b82815260059290921b84018101918181019089841115610e2157600080fd5b948201945b83861015610e4f5785518060060b8114610e405760008081fd5b82529482019490820190610e26565b91880151919650909350505080821115610e6857600080fd5b50610e7585828601610d44565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610eaa57610eaa610bbd565b81667fffffffffffff018313811615610ec557610ec5610bbd565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610efc57610efc610ecf565b667fffffffffffff19821460001982141615610f1a57610f1a610bbd565b90059392505050565b6000600160ff1b821415610f3957610f39610bbd565b5060000390565b60008160020b627fffff19811415610f5a57610f5a610bbd565b60000392915050565b600082610f7257610f72610ecf565b500490565b600082610f8657610f86610ecf565b50069056fea2646970667358221220d6fed705ed46d18dae159a22c722e9aeed52e439bd366bf546b78a194cfd204064736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100365760003560e01c80633bbe42751461003b578063a1a73faf14610060575b600080fd5b61004e610049366004610aec565b610073565b60405190815260200160405180910390f35b61004e61006e366004610b8b565b61015d565b60006002825111156100cc5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101325760006100fb836000815181106100ee576100ee610ba7565b602002602001015161015d565b90506000610115846001815181106100ee576100ee610ba7565b905061012a8282670de0b6b3a764000061018e565b949350505050565b81516001141561015857610152826000815181106100ee576100ee610ba7565b92915050565b919050565b6000806101728360000151846040015161030a565b60208401519091501561012a82670de0b6b3a7640000836104e1565b6000808060001985870985870292508281108382030391505080600014156101c857600084116101bd57600080fd5b508290049050610303565b8084116101d457600080fd5b6000848688098084039381119092039190506000856101f581196001610bd3565b169586900495938490049360008190030460010190506102158184610beb565b909317926000610226876003610beb565b60021890506102358188610beb565b610240906002610c0a565b61024a9082610beb565b90506102568188610beb565b610261906002610c0a565b61026b9082610beb565b90506102778188610beb565b610282906002610c0a565b61028c9082610beb565b90506102988188610beb565b6102a3906002610c0a565b6102ad9082610beb565b90506102b98188610beb565b6102c4906002610c0a565b6102ce9082610beb565b90506102da8188610beb565b6102e5906002610c0a565b6102ef9082610beb565b90506102fb8186610beb565b955050505050505b9392505050565b600063ffffffff821661038857826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610355573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103799190610c33565b50949550610152945050505050565b6040805160028082526060820183526000926020830190803683370190505090506103b4836001610cd2565b816000815181106103c7576103c7610ba7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106103f6576103f6610ba7565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd9061043a908590600401610cfa565b600060405180830381865afa158015610457573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261047f9190810190610db3565b5090506104d88460030b8260008151811061049c5761049c610ba7565b6020026020010151836001815181106104b7576104b7610ba7565b60200260200101516104c99190610e7f565b6104d39190610ee5565b6105b0565b95945050505050565b60006001600160801b036001600160a01b0385161161055457600061050f6001600160a01b03861680610beb565b905082156105345761052f600160c01b856001600160801b03168361018e565b61054c565b61054c81856001600160801b0316600160c01b61018e565b915050610303565b60006105736001600160a01b038616806801000000000000000061018e565b9050821561059857610593600160801b856001600160801b03168361018e565b6104d8565b6104d881856001600160801b0316600160801b61018e565b60008060008360020b126105c7578260020b6105d4565b8260020b6105d490610f23565b90506105e3620d89e719610f40565b62ffffff1681111561061b5760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064016100c3565b60006001821661062f57600160801b610641565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561068057608061067b826ffff97272373d413259a46990580e213a610beb565b901c90505b60048216156106aa5760806106a5826ffff2e50f5f656932ef12357cf3c7fdcc610beb565b901c90505b60088216156106d45760806106cf826fffe5caca7e10e4e61c3624eaa0941cd0610beb565b901c90505b60108216156106fe5760806106f9826fffcb9843d60f6159c9db58835c926644610beb565b901c90505b6020821615610728576080610723826fff973b41fa98c081472e6896dfb254c0610beb565b901c90505b604082161561075257608061074d826fff2ea16466c96a3843ec78b326b52861610beb565b901c90505b608082161561077c576080610777826ffe5dee046a99a2a811c461f1969c3053610beb565b901c90505b6101008216156107a75760806107a2826ffcbe86c7900a88aedcffc83b479aa3a4610beb565b901c90505b6102008216156107d25760806107cd826ff987a7253ac413176f2b074cf7815e54610beb565b901c90505b6104008216156107fd5760806107f8826ff3392b0822b70005940c7a398e4b70f3610beb565b901c90505b610800821615610828576080610823826fe7159475a2c29b7443b29c7fa6e889d9610beb565b901c90505b61100082161561085357608061084e826fd097f3bdfd2022b8845ad8f792aa5825610beb565b901c90505b61200082161561087e576080610879826fa9f746462d870fdf8a65dc1f90e061e5610beb565b901c90505b6140008216156108a95760806108a4826f70d869a156d2a1b890bb3df62baf32f7610beb565b901c90505b6180008216156108d45760806108cf826f31be135f97d08fd981231505542fcfa6610beb565b901c90505b620100008216156109005760806108fb826f09aa508b5b7a84e1c677de54f3e99bc9610beb565b901c90505b6202000082161561092b576080610926826e5d6af8dedb81196699c329225ee604610beb565b901c90505b62040000821615610955576080610950826d2216e584f5fa1ea926041bedfe98610beb565b901c90505b6208000082161561097d576080610978826b048a170391f7dc42444e8fa2610beb565b901c90505b60008460020b13156109985761099581600019610f63565b90505b6109a764010000000082610f77565b156109b35760016109b6565b60005b61012a9060ff16602083901c610bd3565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a0657610a066109c7565b604052919050565b600067ffffffffffffffff821115610a2857610a286109c7565b5060051b60200190565b6001600160a01b0381168114610a4757600080fd5b50565b8015158114610a4757600080fd5b600060a08284031215610a6a57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a8d57610a8d6109c7565b6040529050808235610a9e81610a32565b81526020830135610aae81610a4a565b6020820152604083013563ffffffff81168114610aca57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b60006020808385031215610aff57600080fd5b823567ffffffffffffffff811115610b1657600080fd5b8301601f81018513610b2757600080fd5b8035610b3a610b3582610a0e565b6109dd565b81815260a09182028301840191848201919088841115610b5957600080fd5b938501935b83851015610b7f57610b708986610a58565b83529384019391850191610b5e565b50979650505050505050565b600060a08284031215610b9d57600080fd5b6103038383610a58565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60008219821115610be657610be6610bbd565b500190565b6000816000190483118215151615610c0557610c05610bbd565b500290565b600082821015610c1c57610c1c610bbd565b500390565b805161ffff8116811461015857600080fd5b600080600080600080600060e0888a031215610c4e57600080fd5b8751610c5981610a32565b8097505060208801518060020b8114610c7157600080fd5b9550610c7f60408901610c21565b9450610c8d60608901610c21565b9350610c9b60808901610c21565b925060a088015160ff81168114610cb157600080fd5b60c0890151909250610cc281610a4a565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610cf157610cf1610bbd565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610d3857835163ffffffff1683529284019291840191600101610d16565b50909695505050505050565b600082601f830112610d5557600080fd5b81516020610d65610b3583610a0e565b82815260059290921b84018101918181019086841115610d8457600080fd5b8286015b84811015610da8578051610d9b81610a32565b8352918301918301610d88565b509695505050505050565b60008060408385031215610dc657600080fd5b825167ffffffffffffffff80821115610dde57600080fd5b818501915085601f830112610df257600080fd5b81516020610e02610b3583610a0e565b82815260059290921b84018101918181019089841115610e2157600080fd5b948201945b83861015610e4f5785518060060b8114610e405760008081fd5b82529482019490820190610e26565b91880151919650909350505080821115610e6857600080fd5b50610e7585828601610d44565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610eaa57610eaa610bbd565b81667fffffffffffff018313811615610ec557610ec5610bbd565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610efc57610efc610ecf565b667fffffffffffff19821460001982141615610f1a57610f1a610bbd565b90059392505050565b6000600160ff1b821415610f3957610f39610bbd565b5060000390565b60008160020b627fffff19811415610f5a57610f5a610bbd565b60000392915050565b600082610f7257610f72610ecf565b500490565b600082610f8657610f86610ecf565b50069056fea2646970667358221220d6fed705ed46d18dae159a22c722e9aeed52e439bd366bf546b78a194cfd204064736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/UniswapPricingLibrary.json b/packages/contracts/deployments/bsc/UniswapPricingLibrary.json new file mode 100644 index 000000000..754fcda49 --- /dev/null +++ b/packages/contracts/deployments/bsc/UniswapPricingLibrary.json @@ -0,0 +1,133 @@ +{ + "address": "0x0b65C94CfF84afa6D9CE3D287b1227D9Cc7CdfB7", + "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": "0x9893aa00310239964b8df05dce0e0161a25c2aa7e66d468fa65afa3f9a695b0b", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x0b65C94CfF84afa6D9CE3D287b1227D9Cc7CdfB7", + "transactionIndex": 69, + "gasUsed": "905026", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x679d31f9174940b3e623392fd0cc4683e097fa4388c8151c0fc6b74aaa39042d", + "transactionHash": "0x9893aa00310239964b8df05dce0e0161a25c2aa7e66d468fa65afa3f9a695b0b", + "logs": [], + "blockNumber": 81086317, + "cumulativeGasUsed": "10921968", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/UniswapPricingLibrary.sol\":\"UniswapPricingLibrary\"},\"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/UniswapPricingLibrary.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 UniswapPricingLibrary \\n{\\n \\n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRouteConfig.pool,\\n _poolRouteConfig.twapInterval\\n );\\n\\n //This is the token 1 per token 0 price\\n uint256 sqrtPrice = FullMath.mulDiv(\\n sqrtPriceX96,\\n STANDARD_EXPANSION_FACTOR,\\n 2**96\\n );\\n\\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\\n\\n uint256 price = _poolRouteConfig.zeroForOne\\n ? sqrtPrice * sqrtPrice\\n : sqrtPriceInverse * sqrtPriceInverse;\\n\\n return price / STANDARD_EXPANSION_FACTOR;\\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\":\"0x89fa90d3bba54e357a693f9e0ea96920edfd60c16f8a6a77a32892f4cafd60f3\",\"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": "0x610f6961003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/UniswapPricingLibraryV2.json b/packages/contracts/deployments/bsc/UniswapPricingLibraryV2.json new file mode 100644 index 000000000..4fba786d2 --- /dev/null +++ b/packages/contracts/deployments/bsc/UniswapPricingLibraryV2.json @@ -0,0 +1,133 @@ +{ + "address": "0x0AeeeD450EcCaFaA140222De43963B179B514540", + "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": "0x9391a132f45f473252eaf099b5501b35d6854766a0e08ba42fb138b38c6ead4a", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x0AeeeD450EcCaFaA140222De43963B179B514540", + "transactionIndex": 54, + "gasUsed": "928175", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x0e631764439a6fe7cae5c18233d3b88dc38731c7e595687564b86bb7165bd462", + "transactionHash": "0x9391a132f45f473252eaf099b5501b35d6854766a0e08ba42fb138b38c6ead4a", + "logs": [], + "blockNumber": 81088711, + "cumulativeGasUsed": "6084603", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/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\"},\"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\\n \\n \\n// Libraries \\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x8d3fc2a832e4d6af64a0bd3a94aa3b86fe2324b95b702d196bc053c4b4e334e1\",\"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": "0x610fd461003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/V2Calculations.json b/packages/contracts/deployments/bsc/V2Calculations.json new file mode 100644 index 000000000..c9cdabc4d --- /dev/null +++ b/packages/contracts/deployments/bsc/V2Calculations.json @@ -0,0 +1,149 @@ +{ + "address": "0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed", + "abi": [ + { + "inputs": [ + { + "internalType": "uint32", + "name": "_acceptedTimestamp", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_paymentCycle", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_loanDuration", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_lastRepaidTimestamp", + "type": "uint32" + }, + { + "internalType": "enum PaymentCycleType", + "name": "_bidPaymentCycleType", + "type": "PaymentCycleType" + } + ], + "name": "calculateNextDueDate", + "outputs": [ + { + "internalType": "uint32", + "name": "dueDate_", + "type": "uint32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "enum PaymentType", + "name": "_type", + "type": "PaymentType" + }, + { + "internalType": "enum PaymentCycleType", + "name": "_cycleType", + "type": "PaymentCycleType" + }, + { + "internalType": "uint256", + "name": "_principal", + "type": "uint256" + }, + { + "internalType": "uint32", + "name": "_duration", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_paymentCycle", + "type": "uint32" + }, + { + "internalType": "uint16", + "name": "_apr", + "type": "uint16" + } + ], + "name": "calculatePaymentCycleAmount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + } + ], + "transactionHash": "0xe473aae67d590c0059162b2a763be88ad26bc0a146f004ebcb902b4f7a6b8575", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed", + "transactionIndex": 25, + "gasUsed": "1135180", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xce421d25ae93b965cc3a9b218faddd6c4f11934b7742faa2a54351a383344e68", + "transactionHash": "0xe473aae67d590c0059162b2a763be88ad26bc0a146f004ebcb902b4f7a6b8575", + "logs": [], + "blockNumber": 81086224, + "cumulativeGasUsed": "7417564", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"_acceptedTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_loanDuration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_lastRepaidTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_bidPaymentCycleType\",\"type\":\"PaymentCycleType\"}],\"name\":\"calculateNextDueDate\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"dueDate_\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"enum PaymentType\",\"name\":\"_type\",\"type\":\"PaymentType\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_cycleType\",\"type\":\"PaymentCycleType\"},{\"internalType\":\"uint256\",\"name\":\"_principal\",\"type\":\"uint256\"},{\"internalType\":\"uint32\",\"name\":\"_duration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint16\",\"name\":\"_apr\",\"type\":\"uint16\"}],\"name\":\"calculatePaymentCycleAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"params\":{\"_bid\":\"The loan bid struct to get the owed amount for.\",\"_paymentCycleType\":\"The payment cycle type of the loan (Seconds or Monthly).\",\"_timestamp\":\"The timestamp at which to get the owed amount at.\"}},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"params\":{\"_apr\":\"The annual percentage rate of the loan.\",\"_cycleType\":\"The cycle type set for the loan. (Seconds or Monthly)\",\"_duration\":\"The length of the loan.\",\"_paymentCycle\":\"The length of the loan's payment cycle.\",\"_principal\":\"The starting amount that is owed on the loan.\",\"_type\":\"The payment type of the loan.\"}}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"notice\":\"Calculates the amount owed for a loan.\"},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"notice\":\"Calculates the amount owed for a loan for the next payment cycle.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/V2Calculations.sol\":\"V2Calculations\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@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\",\"keccak256\":\"0x2c0b89cef83f353c6f9488c013d8a5968587ffdd6dfc26aad53774214b97e229\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc6cef87559d0aeffdf0a99803de655938a7779ec0a3cd5d4383483ad85565a09\",\"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\"},\"@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\",\"keccak256\":\"0x52a8cfb0f5239d11b457dcdd1b326992ef672714ca8da71a157255bddd13f3ad\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x0f633a0223d9a1dcccfcf38a64c9de0874dfcbfac0c6941ccf074d63a2ce0e1e\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc3ff3f5c4584e1d9a483ad7ced51ab64523201f4e3d3c65293e4ca8aeb77a961\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x30aabe18188500137c312a4645ae5030e6edbb73ca3a04141b18f4f9a65aec62\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x58734812c9549a2d53d86ac6349b2fba615460732145e863ef9d0c8dc3712d08\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x7d80ce49d143f2f509e1992ed41200e07376bea48950e3674db71a343882f2c8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xceb1ea2ef4c6e2ad7986db84de49c959e8d59844563d27daca5b8d78b732a8f7\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2a17561a47cb3517f2820d68d9bbcd86dcd21c59cad7208581004ecd91d5478a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8d6e50fd460912231e53135b4459aa2f6f16007ae8deb32bc2cee1e88311a8d8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xc5b554eea7e17e47acc632cab40894bac2d2699864fdccc61e08fa8f546c0437\"},\"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\",\"keccak256\":\"0xf194df8ea9946a5bb3300223629b7e4959c1f20bacba27b3dc5f6dd2a160147a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x78009ffb3737ab7615a1e38a26635d6c06b65b7b7959af46d6ef840d220e70cf\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8452535763bfb5c529a0089b8b669d77cc4e1e333b526b89b5d42ab491fb4312\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2781319be7a96f56966c601c061849fa94dbf9af5ad80a20c40b879a8d03f14a\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x61139261003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)": { + "params": { + "_bid": "The loan bid struct to get the owed amount for.", + "_paymentCycleType": "The payment cycle type of the loan (Seconds or Monthly).", + "_timestamp": "The timestamp at which to get the owed amount at." + } + }, + "calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)": { + "params": { + "_apr": "The annual percentage rate of the loan.", + "_cycleType": "The cycle type set for the loan. (Seconds or Monthly)", + "_duration": "The length of the loan.", + "_paymentCycle": "The length of the loan's payment cycle.", + "_principal": "The starting amount that is owed on the loan.", + "_type": "The payment type of the loan." + } + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": { + "calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)": { + "notice": "Calculates the amount owed for a loan." + }, + "calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)": { + "notice": "Calculates the amount owed for a loan for the next payment cycle." + } + }, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/bsc/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json b/packages/contracts/deployments/bsc/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json new file mode 100644 index 000000000..be5b16311 --- /dev/null +++ b/packages/contracts/deployments/bsc/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json @@ -0,0 +1,890 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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 bool public liquidationsPaused; \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 \"oSCF\"\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, \"IRL\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"LTP\"); \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, \"PRL\");\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 \"ST\"\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, \"B\" );\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, \"SM\" );\n \n if(!firstDepositMade){\n require(msg.sender == owner(), \"F.\");\n require( sharesAmount_>= 1e6, \"SA\" );\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 \"CT\"\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 \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"BC\"\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 ,\"W\");\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 require(!liquidationsPaused );\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 );\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() external 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 \"Ldt\"\n );\n require(\n block.timestamp > _loanDefaultedTimestamp,\n \"Ldp\"\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\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pauseLiquidations() public virtual onlyProtocolPauser {\n require(!liquidationsPaused);\n liquidationsPaused = true;\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop.\n */\n function unpauseLiquidations() public virtual onlyProtocolPauser {\n\n require(liquidationsPaused);\n\n setLastUnpausedAt();\n liquidationsPaused = false;\n }\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\n// import \"forge-std/console.sol\"; // Not needed for Hardhat deployment\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\n//import \"forge-std/console.sol\";\n \n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index f37a4cbe0..4f50ba812 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -36,7 +36,7 @@ import rrequire from 'helpers/rrequire' import semver from 'semver' // import { logger as tenderlyLogger } from 'tenderly/utils/logger' -const NODE_VERSION = 'v16' +const NODE_VERSION = '>=20' if (!semver.satisfies(process.version, NODE_VERSION)) throw new Error( `Incorrect NodeJS version being used (${process.version}). Expected: ${NODE_VERSION}` @@ -105,6 +105,7 @@ type NetworkNames = | 'mainnet-live-fork' | 'polygon' | 'arbitrum' + | 'bsc' | 'base' | 'mantle' | 'optimism' @@ -138,7 +139,9 @@ const networkUrls: Record = { (ALCHEMY_API_KEY ? `https://arb-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}` : ''), - + bsc: + process.env.BSC_RPC_URL ?? 'https://bsc-dataseed1.binance.org', + base: process.env.BASE_RPC_URL ?? (ALCHEMY_API_KEY @@ -227,6 +230,7 @@ export default { mainnet: process.env.ETHERSCANV2_VERIFY_API_KEY, polygon: process.env.ETHERSCANV2_VERIFY_API_KEY, arbitrumOne: process.env.ETHERSCANV2_VERIFY_API_KEY, + bsc: process.env.BSCSCAN_VERIFY_API_KEY, base: process.env.ETHERSCANV2_VERIFY_API_KEY, optimism: process.env.ETHERSCANV2_VERIFY_API_KEY, //using the v2 api katana: process.env.ETHERSCANV2_VERIFY_API_KEY, //using the v2 api @@ -281,6 +285,14 @@ export default { browserURL: 'https://arbiscan.io', }, }, + { + network: 'bsc', + chainId: 56, + urls: { + apiURL: 'https://api.bscscan.com/api', + browserURL: 'https://bscscan.com', + }, + }, { @@ -387,10 +399,6 @@ export default { ], }, - ovm: { - solcVersion: '0.8.4', - }, - contractSizer: { runOnCompile: !skipContractSizer, alphaSort: false, @@ -436,6 +444,7 @@ export default { 5000: '0x4496c03dA72386255Bf4af60b3CCe07787d3dCC2', 8453: '0x2f74c448CF6d613bEE183fE35dB0c9AC5084F66A', 42161: '0xD9149bfBfB29cC175041937eF8161600b464051B', + 56: '0x058057c8A9Eb3B93d9F3638d047C98034F45f95E', 11155111: '0xb1ff461BB751B87f4F791201a29A8cFa9D30490c', 999:'0x004573E17574634A48CA808CF1df75f01e906E43' }, @@ -451,6 +460,7 @@ export default { 5000: '0x6BBf498C429C51d05bcA3fC67D2C720B15FC73B8', 8453: '0x6BBf498C429C51d05bcA3fC67D2C720B15FC73B8', 42161: '0x6BBf498C429C51d05bcA3fC67D2C720B15FC73B8', + 56: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534', 11155111: '0xFe5394B67196EA95301D6ECB5389E98A02984cC2', 999: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534' }, @@ -560,6 +570,17 @@ export default { }, }, }), + bsc: networkConfig({ + url: networkUrls.bsc, + chainId: 56, + live: true, + + verify: { + etherscan: { + apiKey: process.env.BSCSCAN_VERIFY_API_KEY, + }, + }, + }), base: networkConfig({ url: networkUrls.base, chainId: 8453, diff --git a/packages/contracts/helpers/ecosystem-contracts-lookup.ts b/packages/contracts/helpers/ecosystem-contracts-lookup.ts index b61724f23..a031d582e 100644 --- a/packages/contracts/helpers/ecosystem-contracts-lookup.ts +++ b/packages/contracts/helpers/ecosystem-contracts-lookup.ts @@ -34,6 +34,9 @@ export function get_ecosystem_contract_address( case 'hyperevm': uniswapV3FactoryAddress = '0xFf7B3e8C00e57ea31477c32A5B52a58Eea47b072' break + case 'bsc': + uniswapV3FactoryAddress = '0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865' // PancakeSwap V3 + break default: return undefined } @@ -71,6 +74,9 @@ export function get_ecosystem_contract_address( case 'hyperevm': weth9Address = '0x1fbccdc677c10671ee50b46c61f0f7d135112450' break + case 'bsc': + weth9Address = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c' // WBNB + break default: return undefined diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 9c6c88f6c..d2bef5f96 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -59,8 +59,6 @@ "build/**/*" ], "devDependencies": { - "@eth-optimism/hardhat-ovm": "^0.2.2", - "@ethereumjs/vm": "^5.5.3", "@ledgerhq/hw-app-eth": "6.45.10", "@ledgerhq/hw-transport-node-hid": "6.29.8", "@nomicfoundation/hardhat-ethers": "^3.1.0", @@ -78,52 +76,49 @@ "@types/ethereumjs-abi": "^0.6.3", "@types/fs-extra": "^9.0.11", "@types/mocha": "^9.0.0", - "@types/node": "^16.11.1", + "@types/node": "^20.0.0", "@types/semver": "^7.3.9", - "@typescript-eslint/eslint-plugin": "^5.5.0", - "@typescript-eslint/parser": "^5.5.0", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", "chai": "^4.3.4", "chai-as-promised": "^7.1.1", "chalk": "^4.1.1", "disklet": "^0.5.0", "dotenv": "^10.0.0", - "eslint": "^7.32.0", + "eslint": "^8.56.0", "eslint-config-prettier": "^8.3.0", "eslint-config-standard-kit": "0.15.1", "eslint-plugin-import": "^2.25.2", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "eslint-plugin-unused-imports": "^2.0.0", + "eslint-plugin-unused-imports": "^3.0.0", "eth-sig-util": "^3.0.1", - "ethereum-waffle": "^3.4.0", "ethereumjs-util": "^7.1.5", "ethers": "^6.7.0", "fs-extra": "^10.0.0", - "ganache-cli": "^6.12.2", - "hardhat": "^2.16.1", + "hardhat": "^2.22.0", "hardhat-contract-sizer": "^2.1.1", "hardhat-deploy": "^0.11.34", - "hardhat-deploy-ethers": "^0.4.1", "hardhat-gas-reporter": "^1.0.4", "hardhat-shorthand": "^1.0.0", "mocha": "^9.1.3", "moment": "^2.29.1", "mustache": "^4.2.0", "node-watch": "^0.7.1", - "prettier": "^2.4.1", - "prettier-plugin-solidity": "^1.0.0-beta.19", + "prettier": "^3.2.0", + "prettier-plugin-solidity": "^1.3.0", "qrcode-terminal": "^0.12.0", "rlp": "^2.2.7", "semver": "^7.3.5", "solhint": "^3.3.6", "solhint-plugin-prettier": "^0.0.5", - "solidity-coverage": "^0.7.17", + "solidity-coverage": "^0.8.0", "solidity-shell": "^0.0.11", "ts-node": "^10.3.0", "tsconfig-paths": "^3.11.0", "typechain": "^8.1.1", - "typescript": "^4.3.4" + "typescript": "^5.4.0" }, "installConfig": { "hoistingLimits": "workspaces" diff --git a/packages/subgraph-pool-v2/package.json b/packages/subgraph-pool-v2/package.json index a361105cc..ee1a0efd7 100644 --- a/packages/subgraph-pool-v2/package.json +++ b/packages/subgraph-pool-v2/package.json @@ -28,21 +28,21 @@ "@types/prompts": "^2.4.4", "@types/semver": "^7.5.0", "@types/uuid": "^9.0.2", - "@typescript-eslint/eslint-plugin": "^5.5.0", - "@typescript-eslint/parser": "^5.5.0", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", "assemblyscript": "^0.27.1", "async-mutex": "^0.4.0", "axios": "^1.4.0", "cleaners": "^0.3.16", "cli-progress": "^3.12.0", - "eslint": "^7.32.0", + "eslint": "^8.56.0", "eslint-config-prettier": "^8.3.0", "eslint-config-standard-kit": "0.15.1", "eslint-plugin-import": "^2.25.2", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "eslint-plugin-unused-imports": "^2.0.0", + "eslint-plugin-unused-imports": "^3.0.0", "hbs-cli": "^1.4.1", "json": "^11.0.0", "matchstick-as": "^0.4.0", @@ -50,7 +50,7 @@ "prompts": "^2.4.2", "semver": "^7.5.4", "ts-node": "^10.9.1", - "typescript": "^4.9.4", + "typescript": "^5.4.0", "uuid": "^9.0.0", "ws": "^8.13.0" } diff --git a/packages/subgraph-pool/package.json b/packages/subgraph-pool/package.json index 37c5510c2..eb5175c9c 100644 --- a/packages/subgraph-pool/package.json +++ b/packages/subgraph-pool/package.json @@ -28,21 +28,21 @@ "@types/prompts": "^2.4.4", "@types/semver": "^7.5.0", "@types/uuid": "^9.0.2", - "@typescript-eslint/eslint-plugin": "^5.5.0", - "@typescript-eslint/parser": "^5.5.0", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", "assemblyscript": "^0.27.1", "async-mutex": "^0.4.0", "axios": "^1.4.0", "cleaners": "^0.3.16", "cli-progress": "^3.12.0", - "eslint": "^7.32.0", + "eslint": "^8.56.0", "eslint-config-prettier": "^8.3.0", "eslint-config-standard-kit": "0.15.1", "eslint-plugin-import": "^2.25.2", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "eslint-plugin-unused-imports": "^2.0.0", + "eslint-plugin-unused-imports": "^3.0.0", "hbs-cli": "^1.4.1", "json": "^11.0.0", "matchstick-as": "^0.4.0", @@ -50,7 +50,7 @@ "prompts": "^2.4.2", "semver": "^7.5.4", "ts-node": "^10.9.1", - "typescript": "^4.9.4", + "typescript": "^5.4.0", "uuid": "^9.0.0", "ws": "^8.13.0" } diff --git a/packages/subgraph/package.json b/packages/subgraph/package.json index 6a6171632..93149e77c 100644 --- a/packages/subgraph/package.json +++ b/packages/subgraph/package.json @@ -28,21 +28,21 @@ "@types/prompts": "^2.4.4", "@types/semver": "^7.5.0", "@types/uuid": "^9.0.2", - "@typescript-eslint/eslint-plugin": "^5.5.0", - "@typescript-eslint/parser": "^5.5.0", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", "assemblyscript": "^0.27.1", "async-mutex": "^0.4.0", "axios": "^1.4.0", "cleaners": "^0.3.16", "cli-progress": "^3.12.0", - "eslint": "^7.32.0", + "eslint": "^8.56.0", "eslint-config-prettier": "^8.3.0", "eslint-config-standard-kit": "0.15.1", "eslint-plugin-import": "^2.25.2", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-simple-import-sort": "^7.0.0", - "eslint-plugin-unused-imports": "^2.0.0", + "eslint-plugin-unused-imports": "^3.0.0", "hbs-cli": "^1.4.1", "json": "^11.0.0", "matchstick-as": "^0.4.0", @@ -50,7 +50,7 @@ "prompts": "^2.4.2", "semver": "^7.5.4", "ts-node": "^10.9.1", - "typescript": "^4.9.4", + "typescript": "^5.4.0", "uuid": "^9.0.0", "ws": "^8.13.0" } From 10b56b04430e4e9716ff40afbf4e4178599ae67f Mon Sep 17 00:00:00 2001 From: andy Date: Sat, 14 Feb 2026 21:14:06 -0500 Subject: [PATCH 39/46] adding pancakeswap info --- .../upgrades/36_transfer_bsc_ownership.ts | 61 +++++++++++++++++++ .../helpers/ecosystem-contracts-lookup.ts | 8 ++- 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 packages/contracts/deploy/upgrades/36_transfer_bsc_ownership.ts diff --git a/packages/contracts/deploy/upgrades/36_transfer_bsc_ownership.ts b/packages/contracts/deploy/upgrades/36_transfer_bsc_ownership.ts new file mode 100644 index 000000000..654db5a48 --- /dev/null +++ b/packages/contracts/deploy/upgrades/36_transfer_bsc_ownership.ts @@ -0,0 +1,61 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' +import { logTxLink } from 'helpers/logTxLink' + +const deployFn: DeployFunction = async (hre) => { + hre.log('----------') + hre.log('') + hre.log('BSC: Transferring ownership of contracts to Safe Multisig') + hre.log('') + + const { deployer, protocolOwnerSafe } = await hre.getNamedAccounts() + + const contractNames = [ + 'SmartCommitmentForwarder', + 'LenderCommitmentGroupFactory_V2', + 'CollateralManager', + ] + + for (const contractName of contractNames) { + const contract = await hre.contracts.get(contractName) + const currentOwner = await contract.owner() + + if (deployer === currentOwner) { + hre.log(` Transferring ${contractName} ownership...`) + const tx = await contract.transferOwnership(protocolOwnerSafe) + await tx.wait(1) + + hre.log( + ` ✅ ${contractName} ownership transferred to Safe Multisig (${protocolOwnerSafe})` + ) + await logTxLink(hre, tx.hash) + } else if (protocolOwnerSafe === currentOwner) { + hre.log( + ` ✅ ${contractName} ownership is already set to the Safe Multisig` + ) + } else { + hre.log( + ` ⚠️ ${contractName} is owned by ${currentOwner} (not deployer). Skipping.` + ) + } + } + + hre.log('') + hre.log('done.') + hre.log('----------') + + return true +} + +// tags and deployment +deployFn.id = 'bsc:transfer-ownership-to-safe' +deployFn.tags = ['bsc', 'bsc:transfer-ownership-to-safe'] +deployFn.dependencies = [ + 'smart-commitment-forwarder:deploy', + 'lender-commitment-group-factory-v2:deploy', + 'collateral:manager:deploy', +] + +deployFn.skip = async (hre) => { + return !hre.network.live || hre.network.name !== 'bsc' +} +export default deployFn diff --git a/packages/contracts/helpers/ecosystem-contracts-lookup.ts b/packages/contracts/helpers/ecosystem-contracts-lookup.ts index a031d582e..2d36181b0 100644 --- a/packages/contracts/helpers/ecosystem-contracts-lookup.ts +++ b/packages/contracts/helpers/ecosystem-contracts-lookup.ts @@ -113,6 +113,9 @@ export function get_ecosystem_contract_address( case 'hyperevm': swapRouterAddress = '0x1EbDFC75FfE3ba3de61E7138a3E8706aC841Af9B' break + case 'bsc': + swapRouterAddress = '0x1b81D678ffb9C0263b24A97847620C99d213eB14' // PancakeSwap V3 + break default: return undefined //throw new Error('No swap factory address found for this network') @@ -150,7 +153,10 @@ export function get_ecosystem_contract_address( break case 'hyperevm': quoterAddress = ' ' //'0x239F11a7A3E08f2B8110D4CA9F6B95d4c8865258' - break + break + case 'bsc': + quoterAddress = '0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997' // PancakeSwap V3 + break default: return undefined //throw new Error('No swap factory address found for this network') From eeecec2560ccc441050708f7b5e8a798e8c55bb7 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 19 Feb 2026 21:35:59 -0500 Subject: [PATCH 40/46] config for apechain --- .../deploy/admin/timelock_controller.ts | 2 +- .../deploy_alpha.ts | 2 +- .../lender_commitment_group_v2_beacon.ts | 2 +- .../lender_groups_factory_v2.ts | 2 +- .../uniswap_pricing_libraryV2.ts | 2 +- .../deploy/oracle/mock_hypernative_oracle.ts | 2 +- .../deploy/pricing/uniswap_pricing_helper.ts | 2 +- .../smart_commitment_forwarder/deploy.ts | 2 +- .../teller_v2/protocol_pausing_manager.ts | 2 +- .../37_transfer_apechain_ownership.ts | 61 +++++++++++++++++++ packages/contracts/hardhat.config.ts | 31 +++++++++- .../helpers/ecosystem-contracts-lookup.ts | 12 ++++ .../contracts/helpers/gnosis-safe-helpers.ts | 5 +- packages/subgraph-pool-v2/README.md | 7 ++- packages/subgraph-pool-v2/subgraph.yaml | 14 ++--- packages/subgraph/README.md | 8 ++- 16 files changed, 132 insertions(+), 24 deletions(-) create mode 100644 packages/contracts/deploy/upgrades/37_transfer_apechain_ownership.ts diff --git a/packages/contracts/deploy/admin/timelock_controller.ts b/packages/contracts/deploy/admin/timelock_controller.ts index b037a834b..ea85b07c8 100644 --- a/packages/contracts/deploy/admin/timelock_controller.ts +++ b/packages/contracts/deploy/admin/timelock_controller.ts @@ -59,7 +59,7 @@ deployFn.skip = async (hre) => { // return true; //for now return !( hre.network.live && - [ 'hyperevm', 'bsc' ].includes( + [ 'hyperevm', 'bsc', 'apechain' ].includes( hre.network.name ) ) diff --git a/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts b/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts index 94df187b2..ea12592c2 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/deploy_alpha.ts @@ -38,7 +38,7 @@ deployFn.tags = [ deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy'] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc','apechain'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts index b815fb850..cff0cf826 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_commitment_group_v2_beacon.ts @@ -80,6 +80,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) + return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc','apechain'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts index af9b13c08..5e23428b9 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v2/lender_groups_factory_v2.ts @@ -42,6 +42,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc','apechain'].includes(hre.network.name) } export default deployFn \ 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 index cb6660432..a2b140030 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts @@ -14,6 +14,6 @@ deployFn.dependencies = [''] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia', 'polygon' , 'base','arbitrum','mainnet','mainnet_live_fork','optimism','katana','bsc'].includes(hre.network.name) + return !hre.network.live || !['sepolia', 'polygon' , 'base','arbitrum','mainnet','mainnet_live_fork','optimism','katana','bsc','apechain'].includes(hre.network.name) } export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts b/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts index 34de8cf63..1dca84b7f 100644 --- a/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts +++ b/packages/contracts/deploy/oracle/mock_hypernative_oracle.ts @@ -24,6 +24,6 @@ deployFn.id = 'hypernative-oracle-mock:deploy' deployFn.tags = ['hypernative-oracle-mock:deploy'] deployFn.dependencies = [] deployFn.skip = async (hre) => { - return !hre.network.live || !['polygon', 'arbitrum','base','mainnet','bsc'].includes(hre.network.name) + return !hre.network.live || !['polygon', 'arbitrum','base','mainnet','bsc','apechain'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts b/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts index baa527d6b..f600fea05 100644 --- a/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts +++ b/packages/contracts/deploy/pricing/uniswap_pricing_helper.ts @@ -20,7 +20,7 @@ deployFn.tags = ['teller-v2', 'uniswap-pricing-helper:deploy'] deployFn.dependencies = [''] deployFn.skip = async (hre) => { - return !hre.network.live || !['polygon','bsc'].includes(hre.network.name) + return !hre.network.live || !['polygon','bsc','apechain'].includes(hre.network.name) } export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts b/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts index d1b58c04c..a82f33716 100644 --- a/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts +++ b/packages/contracts/deploy/smart_commitment_forwarder/deploy.ts @@ -32,7 +32,7 @@ deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy'] deployFn.skip = async (hre) => { return ( - !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) + !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc','apechain'].includes(hre.network.name) ) } export default deployFn diff --git a/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts b/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts index 5ab62246a..8dc52c3c8 100644 --- a/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts +++ b/packages/contracts/deploy/teller_v2/protocol_pausing_manager.ts @@ -47,7 +47,7 @@ deployFn.dependencies = ['teller-v2:deploy' ] deployFn.skip = async (hre) => { return ( - !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc'].includes(hre.network.name) + !hre.network.live || !['localhost', 'polygon', 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','bsc','apechain'].includes(hre.network.name) ) } export default deployFn diff --git a/packages/contracts/deploy/upgrades/37_transfer_apechain_ownership.ts b/packages/contracts/deploy/upgrades/37_transfer_apechain_ownership.ts new file mode 100644 index 000000000..1eb6b2a79 --- /dev/null +++ b/packages/contracts/deploy/upgrades/37_transfer_apechain_ownership.ts @@ -0,0 +1,61 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' +import { logTxLink } from 'helpers/logTxLink' + +const deployFn: DeployFunction = async (hre) => { + hre.log('----------') + hre.log('') + hre.log('ApeChain: Transferring ownership of contracts to Safe Multisig') + hre.log('') + + const { deployer, protocolOwnerSafe } = await hre.getNamedAccounts() + + const contractNames = [ + 'SmartCommitmentForwarder', + 'LenderCommitmentGroupFactory_V2', + 'CollateralManager', + ] + + for (const contractName of contractNames) { + const contract = await hre.contracts.get(contractName) + const currentOwner = await contract.owner() + + if (deployer === currentOwner) { + hre.log(` Transferring ${contractName} ownership...`) + const tx = await contract.transferOwnership(protocolOwnerSafe) + await tx.wait(1) + + hre.log( + ` ✅ ${contractName} ownership transferred to Safe Multisig (${protocolOwnerSafe})` + ) + await logTxLink(hre, tx.hash) + } else if (protocolOwnerSafe === currentOwner) { + hre.log( + ` ✅ ${contractName} ownership is already set to the Safe Multisig` + ) + } else { + hre.log( + ` ⚠️ ${contractName} is owned by ${currentOwner} (not deployer). Skipping.` + ) + } + } + + hre.log('') + hre.log('done.') + hre.log('----------') + + return true +} + +// tags and deployment +deployFn.id = 'apechain:transfer-ownership-to-safe' +deployFn.tags = ['apechain', 'apechain:transfer-ownership-to-safe'] +deployFn.dependencies = [ + 'smart-commitment-forwarder:deploy', + 'lender-commitment-group-factory-v2:deploy', + 'collateral:manager:deploy', +] + +deployFn.skip = async (hre) => { + return !hre.network.live || hre.network.name !== 'apechain' +} +export default deployFn diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index 4f50ba812..12fcc0730 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -111,6 +111,7 @@ type NetworkNames = | 'optimism' | 'katana' | 'hyperevm' + | 'apechain' | 'sepolia' | 'mumbai' | 'goerli' @@ -158,8 +159,9 @@ const networkUrls: Record = { katana: process.env.KATANA_RPC_URL ?? 'https://rpc.katana.network/', - hyperevm: process.env.HYPEREVM_RPC_URL ?? 'https://rpc.hyperliquid.xyz/evm', + hyperevm: process.env.HYPEREVM_RPC_URL ?? 'https://rpc.hyperliquid.xyz/evm', + apechain: process.env.APECHAIN_RPC_URL ?? 'https://rpc.apechain.com', mantle: 'https://rpc.mantle.xyz', @@ -235,6 +237,7 @@ export default { optimism: process.env.ETHERSCANV2_VERIFY_API_KEY, //using the v2 api katana: process.env.ETHERSCANV2_VERIFY_API_KEY, //using the v2 api hyperevm: process.env.ETHERSCANV2_VERIFY_API_KEY, + apechain: process.env.ETHERSCANV2_VERIFY_API_KEY, mantle: process.env.MANTLE_VERIFY_API_KEY ?? 'xyz', clarity: '', //none ? @@ -321,6 +324,14 @@ export default { }, }, + { + network: 'apechain', + chainId: 33139, + urls: { + apiURL: 'https://api.etherscan.io/v2/api?chainid=33139', + browserURL: 'https://apescan.io', + }, + }, { network: 'clarity', chainId: 66814, @@ -446,7 +457,8 @@ export default { 42161: '0xD9149bfBfB29cC175041937eF8161600b464051B', 56: '0x058057c8A9Eb3B93d9F3638d047C98034F45f95E', 11155111: '0xb1ff461BB751B87f4F791201a29A8cFa9D30490c', - 999:'0x004573E17574634A48CA808CF1df75f01e906E43' + 999:'0x004573E17574634A48CA808CF1df75f01e906E43', + 33139: '0x2BbD69C72b6689F31dd12b93fF59E62632E0eF41' // apechain }, protocolTimelock: { 31337: 8, @@ -462,7 +474,8 @@ export default { 42161: '0x6BBf498C429C51d05bcA3fC67D2C720B15FC73B8', 56: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534', 11155111: '0xFe5394B67196EA95301D6ECB5389E98A02984cC2', - 999: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534' + 999: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534', + 33139: 0 // apechain - TBD after deployment }, }, @@ -659,6 +672,18 @@ export default { }, }), + apechain: networkConfig({ + url: networkUrls.apechain, + chainId: 33139, + live: true, + + verify: { + etherscan: { + apiKey: process.env.ETHERSCANV2_VERIFY_API_KEY, + }, + }, + }), + clarity: networkConfig({ url: networkUrls.clarity, chainId: 66814, diff --git a/packages/contracts/helpers/ecosystem-contracts-lookup.ts b/packages/contracts/helpers/ecosystem-contracts-lookup.ts index 2d36181b0..35f1f142a 100644 --- a/packages/contracts/helpers/ecosystem-contracts-lookup.ts +++ b/packages/contracts/helpers/ecosystem-contracts-lookup.ts @@ -37,6 +37,9 @@ export function get_ecosystem_contract_address( case 'bsc': uniswapV3FactoryAddress = '0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865' // PancakeSwap V3 break + case 'apechain': + uniswapV3FactoryAddress = '0x10aA510d94E094Bd643677bd2964c3EE085Daffc' // Camelot V3 (Algebra) + break default: return undefined } @@ -77,6 +80,9 @@ export function get_ecosystem_contract_address( case 'bsc': weth9Address = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c' // WBNB break + case 'apechain': + weth9Address = '0x48b62137EdfA95a428D35C09E44256a739F6B557' // WAPE + break default: return undefined @@ -116,6 +122,9 @@ export function get_ecosystem_contract_address( case 'bsc': swapRouterAddress = '0x1b81D678ffb9C0263b24A97847620C99d213eB14' // PancakeSwap V3 break + case 'apechain': + swapRouterAddress = '0xC69Dc28924930583024E067b2B3d773018F4EB52' // Camelot V3 + break default: return undefined //throw new Error('No swap factory address found for this network') @@ -157,6 +166,9 @@ export function get_ecosystem_contract_address( case 'bsc': quoterAddress = '0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997' // PancakeSwap V3 break + case 'apechain': + quoterAddress = '0x60A186019F81bFD04aFc16c9C01804a04E79e68B' // Camelot V3 + break default: return undefined //throw new Error('No swap factory address found for this network') diff --git a/packages/contracts/helpers/gnosis-safe-helpers.ts b/packages/contracts/helpers/gnosis-safe-helpers.ts index 9594c0fc9..3615aab20 100644 --- a/packages/contracts/helpers/gnosis-safe-helpers.ts +++ b/packages/contracts/helpers/gnosis-safe-helpers.ts @@ -459,7 +459,8 @@ export class GnosisSafeAdminClient { 'gnosis': 100, 'avalanche': 43114, 'bsc': 56, - 'katana':747474 + 'katana':747474, + 'apechain': 33139 } return chainIds[network] || 1 } @@ -537,6 +538,7 @@ export class GnosisSafeAdminClient { 'avalanche': 'avax', 'bsc': 'bnb', 'katana': 'katana', + 'apechain': 'apechain', } return networkMap[network as string] || 'eth' @@ -556,6 +558,7 @@ export class GnosisSafeAdminClient { 'gnosis': 'https://safe-transaction-gnosis-chain.safe.global', 'avalanche': 'https://safe-transaction-avalanche.safe.global', 'bsc': 'https://safe-transaction-bsc.safe.global', + 'apechain': 'https://safe-transaction-apechain.safe.global', } return networkMap[network] || 'https://safe-transaction-mainnet.safe.global' } diff --git a/packages/subgraph-pool-v2/README.md b/packages/subgraph-pool-v2/README.md index 089685fc9..b616b6e13 100644 --- a/packages/subgraph-pool-v2/README.md +++ b/packages/subgraph-pool-v2/README.md @@ -95,11 +95,16 @@ deploy to goldsky npm run generate katana + + +npm run codegen && npm run build + + npm run generate hyperevm goldsky subgraph deploy teller-pools-v2-hyperevm/0.4.21.2 -goldsky subgraph deploy teller-pools-v2-katana/0.4.21.9 +goldsky subgraph deploy teller-pools-v2-katana/0.4.21.13 ``` diff --git a/packages/subgraph-pool-v2/subgraph.yaml b/packages/subgraph-pool-v2/subgraph.yaml index b2c2d3cc2..fb07b9329 100644 --- a/packages/subgraph-pool-v2/subgraph.yaml +++ b/packages/subgraph-pool-v2/subgraph.yaml @@ -9,11 +9,11 @@ features: dataSources: - kind: ethereum/contract name: Factory - network: matic + network: katana source: abi: Factory - address: "0xA7faf9435810fB571f61e1e116b3F18DE0B3583A" - startBlock: 73129776 + address: "0x3D495036Dfeb1bBfCCabAC74e90e01cDD5C8E578" + startBlock: 6541463 mapping: kind: ethereum/events apiVersion: 0.0.7 @@ -29,11 +29,11 @@ dataSources: handler: handleLenderGroupDeployed - kind: ethereum/contract name: CollateralManager - network: matic + network: katana source: abi: CollateralManager - address: "0x76888a882a4fF57455B5e74B791DD19DF3ba51Bb" - startBlock: 73129776 + address: "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f" + startBlock: 6541463 mapping: kind: ethereum/events apiVersion: 0.0.7 @@ -51,7 +51,7 @@ dataSources: templates: - kind: ethereum/contract name: Pool - network: matic + network: katana source: abi: Pool mapping: diff --git a/packages/subgraph/README.md b/packages/subgraph/README.md index 556e3cf95..06d2c66f7 100644 --- a/packages/subgraph/README.md +++ b/packages/subgraph/README.md @@ -39,7 +39,7 @@ yarn build ``` -yarn handlebars mainnet / polygon / arbitrum / base +yarn handlebars mainnet / polygon / arbitrum / base / katana / hyperevm @@ -65,7 +65,7 @@ graph auth graph deploy tellerv2-arbitrum --version-label 0.4.21-24 - graph deploy teller-v-2-katana --version-label 0.4.21-22 + graph deploy teller-v-2-katana --version-label 0.4.21.6 graph deploy teller-v-2-polygon --version-label 0.4.21-26 graph deploy teller-v-2-optimism --version-label 0.4.21-19 @@ -104,7 +104,9 @@ graph deploy tellerv2-polygon \ graph build (builds the yaml file in /build/ ? not in root ) -goldsky subgraph deploy teller-v2-hyperevm/0.4.21.5 +goldsky subgraph deploy teller-v2-hyperevm/0.4.21.6 + +goldsky subgraph deploy teller-v2-katana/0.4.21.6 From f4a7b5ae38374f96bf738e156ecd43da1f8d6a47 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 19 Feb 2026 22:00:22 -0500 Subject: [PATCH 41/46] deployed teller contracts --- .../.openzeppelin/unknown-33139.json | 3202 +++++++++++++++++ ...38_transfer_apechain_timelock_ownership.ts | 87 + .../contracts/deployments/apechain/.chainId | 1 + .../apechain/.latestDeploymentBlock | 1 + .../deployments/apechain/.migrations.json | 27 + .../deployments/apechain/BorrowSwap.json | 306 ++ .../apechain/CollateralEscrowBeacon.json | 350 ++ .../apechain/CollateralManager.json | 721 ++++ .../deployments/apechain/EscrowVault.json | 101 + .../apechain/HypernativeOracle.json | 737 ++++ .../LenderCommitmentForwarderAlpha.json | 1189 ++++++ .../LenderCommitmentGroupBeaconV2.json | 2017 +++++++++++ .../LenderCommitmentGroupFactory_V2.json | 218 ++ .../deployments/apechain/LenderManager.json | 441 +++ .../apechain/MarketLiquidityRewards.json | 405 +++ .../deployments/apechain/MarketRegistry.json | 1390 +++++++ .../deployments/apechain/MetaForwarder.json | 155 + .../apechain/ProtocolPausingManager.json | 310 ++ .../apechain/ReputationManager.json | 218 ++ .../apechain/SmartCommitmentForwarder.json | 578 +++ .../apechain/SwapRolloverLoan.json | 514 +++ .../deployments/apechain/TellerAS.json | 1089 ++++++ .../apechain/TellerASEIP712Verifier.json | 273 ++ .../apechain/TellerASRegistry.json | 285 ++ .../deployments/apechain/TellerV2.json | 1761 +++++++++ .../apechain/TimelockController.json | 1246 +++++++ .../apechain/UniswapPricingHelper.json | 133 + .../apechain/UniswapPricingLibrary.json | 133 + .../apechain/UniswapPricingLibraryV2.json | 133 + .../deployments/apechain/V2Calculations.json | 149 + .../0734360f150a1a42bdf38edcad8bf3ab.json | 890 +++++ packages/contracts/hardhat.config.ts | 2 +- 32 files changed, 19061 insertions(+), 1 deletion(-) create mode 100644 packages/contracts/.openzeppelin/unknown-33139.json create mode 100644 packages/contracts/deploy/upgrades/38_transfer_apechain_timelock_ownership.ts create mode 100644 packages/contracts/deployments/apechain/.chainId create mode 100644 packages/contracts/deployments/apechain/.latestDeploymentBlock create mode 100644 packages/contracts/deployments/apechain/.migrations.json create mode 100644 packages/contracts/deployments/apechain/BorrowSwap.json create mode 100644 packages/contracts/deployments/apechain/CollateralEscrowBeacon.json create mode 100644 packages/contracts/deployments/apechain/CollateralManager.json create mode 100644 packages/contracts/deployments/apechain/EscrowVault.json create mode 100644 packages/contracts/deployments/apechain/HypernativeOracle.json create mode 100644 packages/contracts/deployments/apechain/LenderCommitmentForwarderAlpha.json create mode 100644 packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV2.json create mode 100644 packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V2.json create mode 100644 packages/contracts/deployments/apechain/LenderManager.json create mode 100644 packages/contracts/deployments/apechain/MarketLiquidityRewards.json create mode 100644 packages/contracts/deployments/apechain/MarketRegistry.json create mode 100644 packages/contracts/deployments/apechain/MetaForwarder.json create mode 100644 packages/contracts/deployments/apechain/ProtocolPausingManager.json create mode 100644 packages/contracts/deployments/apechain/ReputationManager.json create mode 100644 packages/contracts/deployments/apechain/SmartCommitmentForwarder.json create mode 100644 packages/contracts/deployments/apechain/SwapRolloverLoan.json create mode 100644 packages/contracts/deployments/apechain/TellerAS.json create mode 100644 packages/contracts/deployments/apechain/TellerASEIP712Verifier.json create mode 100644 packages/contracts/deployments/apechain/TellerASRegistry.json create mode 100644 packages/contracts/deployments/apechain/TellerV2.json create mode 100644 packages/contracts/deployments/apechain/TimelockController.json create mode 100644 packages/contracts/deployments/apechain/UniswapPricingHelper.json create mode 100644 packages/contracts/deployments/apechain/UniswapPricingLibrary.json create mode 100644 packages/contracts/deployments/apechain/UniswapPricingLibraryV2.json create mode 100644 packages/contracts/deployments/apechain/V2Calculations.json create mode 100644 packages/contracts/deployments/apechain/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json diff --git a/packages/contracts/.openzeppelin/unknown-33139.json b/packages/contracts/.openzeppelin/unknown-33139.json new file mode 100644 index 000000000..1cf679c31 --- /dev/null +++ b/packages/contracts/.openzeppelin/unknown-33139.json @@ -0,0 +1,3202 @@ +{ + "manifestVersion": "3.2", + "admin": { + "address": "0x9C23e308662a1555d83FA6E862a0BAf720A19237", + "txHash": "0x9b0b946e5234dc85a2fdf012a93d22718a7f1814b7edba5bbb6ef56b6e1e5e15" + }, + "proxies": [ + { + "address": "0xe7768f28455eE81D7B415f4F5019A316c27AB445", + "txHash": "0xd6652a090a359c4dee65f71bc7ecb37f0b5366ab57c4d77d992e12685503aa03", + "kind": "transparent" + }, + { + "address": "0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed", + "txHash": "0xa84d0bf1f91dea76a6849b3eb32c9a90ec2cb0f8e5a79bf138785583003537b8", + "kind": "transparent" + }, + { + "address": "0x90D08f8Df66dFdE93801783FF7A36876453DAE75", + "txHash": "0x145f1c9d10a249546f02bb8b7c779e8bba95c12d4de601bf7151d7d7dae11d62", + "kind": "transparent" + }, + { + "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", + "txHash": "0x52c6eb9126c15ee75517d01db512f72b042b23b0b3392f1f3af93ea4719735bd", + "kind": "transparent" + }, + { + "address": "0x0708480670BdE591e275B06Cd19EcaDFC93A1f16", + "txHash": "0x424efe84c9340a420d1df1b7b41b132fbe2f3b97b945b2ccdeddd3eef1e5c2ad", + "kind": "transparent" + }, + { + "address": "0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515", + "txHash": "0x0c414be1fa3b892c087cb87b9c6b133ae39bfd43841de723f693253945f605c5", + "kind": "transparent" + }, + { + "address": "0xa1106d888F1FA689c6935e0983687432eF2a28c1", + "txHash": "0x719c72815d86034751e0d219c8731e7cf62d21a979c246a6e62a4a46485378c2", + "kind": "transparent" + }, + { + "address": "0x7FBCefE4aE4c0C9E70427D0B9F1504Ed39d141BC", + "txHash": "0xff412445c8d7692f8472f2546fbf59387bfb331ccd5aa74bfcbeee47ae5ec080", + "kind": "transparent" + }, + { + "address": "0x7f43c21D4FE1807BF2CF25e6F048A03b57226e03", + "txHash": "0x2e602e44bf768ea756b819e26572332e4b381a7127e95b6df20c22383ad45db7", + "kind": "transparent" + }, + { + "address": "0x48EE9c344d5C6d202F4b3225A694957a3412008d", + "txHash": "0x84b1a9916fc64dd4a489ab58cb3aa39c6afb0293e9cb9ba05b04e15bf12a6961", + "kind": "transparent" + }, + { + "address": "0x0AeeeD450EcCaFaA140222De43963B179B514540", + "txHash": "0xa33a5626479d237b8c7b1279cbbf6762ee4263585303c9015f69dbb7d32d5e88", + "kind": "transparent" + }, + { + "address": "0x357fa5700f67a3DA1EC49ea19F872B3a35fE043D", + "txHash": "0x7f305ae2a6142aa8d4bfe6625bd846dc08b503df62bcb1acfb21313f1bdc2623", + "kind": "transparent" + }, + { + "address": "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa", + "txHash": "0x352879e528664e781286b1b9982223ac3f25038cd151cdd1a672fafd309d7730", + "kind": "transparent" + }, + { + "address": "0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D", + "txHash": "0xdfdd739a69e9844c0c8a1e751478e43df55a5cf6003f17c973c994c1e6d87666", + "kind": "transparent" + } + ], + "impls": { + "ce39878ecd9200ccdebe2ced384987a3a016d16553069380ba583f8183124209": { + "address": "0xfA87381128aAF95fB637BbA0B760bA2f9970c2b5", + "txHash": "0x7a14345f07d2a58df275b0e2e7126ad058427665a58dbbc6d10470c1c9fbee32", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "bidId", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "CollateralEscrowV1", + "src": "contracts/escrow/CollateralEscrowV1.sol:17" + }, + { + "label": "collateralBalances", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_struct(Collateral)51767_storage)", + "contract": "CollateralEscrowV1", + "src": "contracts/escrow/CollateralEscrowV1.sol:19" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_enum(CollateralType)51757": { + "label": "enum CollateralType", + "members": [ + "ERC20", + "ERC721", + "ERC1155" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_struct(Collateral)51767_storage)": { + "label": "mapping(address => struct Collateral)", + "numberOfBytes": "32" + }, + "t_struct(Collateral)51767_storage": { + "label": "struct Collateral", + "members": [ + { + "label": "_collateralType", + "type": "t_enum(CollateralType)51757", + "offset": 0, + "slot": "0" + }, + { + "label": "_amount", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "_tokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "_collateralAddress", + "type": "t_address", + "offset": 0, + "slot": "3" + } + ], + "numberOfBytes": "128" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "032c39add4d0355222025ad6d0b242e0fa061dbd76a18f52856a1551a3cadfac": { + "address": "0x0258eAE8bBEf65c523A78705Fe80a82fD75e258d", + "txHash": "0x4f4dee1cc538b38bb92726f501983bc497d4d8ef2cede72de2352cfcf931fbbb", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "_HASHED_NAME", + "offset": 0, + "slot": "1", + "type": "t_bytes32", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:32" + }, + { + "label": "_HASHED_VERSION", + "offset": 0, + "slot": "2", + "type": "t_bytes32", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:33" + }, + { + "label": "__gap", + "offset": 0, + "slot": "3", + "type": "t_array(t_uint256)50_storage", + "contract": "EIP712Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol:120" + }, + { + "label": "_nonces", + "offset": 0, + "slot": "53", + "type": "t_mapping(t_address,t_uint256)", + "contract": "MinimalForwarderUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:33" + }, + { + "label": "__gap", + "offset": 0, + "slot": "54", + "type": "t_array(t_uint256)49_storage", + "contract": "MinimalForwarderUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol:84" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "de1f061593a314bef6804a965467cde86deacadffc3a47fa8863f782105ebe34": { + "address": "0xE11884953B18F8ddC55875CBDAb71b624779D3bB", + "txHash": "0x21c17aa4f33b858672b1e9a0ef464825f82a81808e02d5384cb4f570a4a94765", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_protocolFee", + "offset": 0, + "slot": "101", + "type": "t_uint16", + "contract": "ProtocolFee", + "src": "contracts/ProtocolFee.sol:8" + }, + { + "label": "__paused", + "offset": 2, + "slot": "101", + "type": "t_bool", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:18" + }, + { + "label": "_protocolPausingManager", + "offset": 3, + "slot": "101", + "type": "t_address", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:20" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "HasProtocolPausingManager", + "src": "contracts/pausing/HasProtocolPausingManager.sol:57" + }, + { + "label": "bidId", + "offset": 0, + "slot": "151", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:92" + }, + { + "label": "bids", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_uint256,t_struct(Bid)44648_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:95" + }, + { + "label": "borrowerBids", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_address,t_array(t_uint256)dyn_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:98" + }, + { + "label": "__lenderVolumeFilled", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_address,t_uint256)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:101" + }, + { + "label": "__totalVolumeFilled", + "offset": 0, + "slot": "155", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:104" + }, + { + "label": "__lendingTokensSet", + "offset": 0, + "slot": "156", + "type": "t_struct(AddressSet)13999_storage", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:107" + }, + { + "label": "marketRegistry", + "offset": 0, + "slot": "158", + "type": "t_contract(IMarketRegistry)49610", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:109" + }, + { + "label": "reputationManager", + "offset": 0, + "slot": "159", + "type": "t_contract(IReputationManager)49705", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:110" + }, + { + "label": "_borrowerBidsActive", + "offset": 0, + "slot": "160", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:113" + }, + { + "label": "bidDefaultDuration", + "offset": 0, + "slot": "161", + "type": "t_mapping(t_uint256,t_uint32)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:115" + }, + { + "label": "bidExpirationTime", + "offset": 0, + "slot": "162", + "type": "t_mapping(t_uint256,t_uint32)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:116" + }, + { + "label": "lenderVolumeFilled", + "offset": 0, + "slot": "163", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:120" + }, + { + "label": "totalVolumeFilled", + "offset": 0, + "slot": "164", + "type": "t_mapping(t_address,t_uint256)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:124" + }, + { + "label": "version", + "offset": 0, + "slot": "165", + "type": "t_uint256", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:126" + }, + { + "label": "uris", + "offset": 0, + "slot": "166", + "type": "t_mapping(t_uint256,t_string_storage)", + "contract": "TellerV2Storage_G0", + "src": "contracts/TellerV2Storage.sol:130" + }, + { + "label": "_trustedMarketForwarders", + "offset": 0, + "slot": "167", + "type": "t_mapping(t_uint256,t_address)", + "contract": "TellerV2Storage_G1", + "src": "contracts/TellerV2Storage.sol:135" + }, + { + "label": "_approvedForwarderSenders", + "offset": 0, + "slot": "168", + "type": "t_mapping(t_address,t_struct(AddressSet)13999_storage)", + "contract": "TellerV2Storage_G1", + "src": "contracts/TellerV2Storage.sol:137" + }, + { + "label": "lenderCommitmentForwarder", + "offset": 0, + "slot": "169", + "type": "t_address", + "contract": "TellerV2Storage_G2", + "src": "contracts/TellerV2Storage.sol:142" + }, + { + "label": "collateralManager", + "offset": 0, + "slot": "170", + "type": "t_contract(ICollateralManager)48330", + "contract": "TellerV2Storage_G3", + "src": "contracts/TellerV2Storage.sol:146" + }, + { + "label": "lenderManager", + "offset": 0, + "slot": "171", + "type": "t_contract(ILenderManager)49339", + "contract": "TellerV2Storage_G4", + "src": "contracts/TellerV2Storage.sol:151" + }, + { + "label": "bidPaymentCycleType", + "offset": 0, + "slot": "172", + "type": "t_mapping(t_uint256,t_enum(PaymentCycleType)54768)", + "contract": "TellerV2Storage_G4", + "src": "contracts/TellerV2Storage.sol:153" + }, + { + "label": "escrowVault", + "offset": 0, + "slot": "173", + "type": "t_contract(IEscrowVault)48831", + "contract": "TellerV2Storage_G5", + "src": "contracts/TellerV2Storage.sol:158" + }, + { + "label": "repaymentListenerForBid", + "offset": 0, + "slot": "174", + "type": "t_mapping(t_uint256,t_address)", + "contract": "TellerV2Storage_G6", + "src": "contracts/TellerV2Storage.sol:162" + }, + { + "label": "__pauserRoleBearer", + "offset": 0, + "slot": "175", + "type": "t_mapping(t_address,t_bool)", + "contract": "TellerV2Storage_G7", + "src": "contracts/TellerV2Storage.sol:166" + }, + { + "label": "__liquidationsPaused", + "offset": 0, + "slot": "176", + "type": "t_bool", + "contract": "TellerV2Storage_G7", + "src": "contracts/TellerV2Storage.sol:167" + }, + { + "label": "protocolFeeRecipient", + "offset": 1, + "slot": "176", + "type": "t_address", + "contract": "TellerV2Storage_G8", + "src": "contracts/TellerV2Storage.sol:171" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "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_array(t_uint256)dyn_storage": { + "label": "uint256[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(ICollateralManager)48330": { + "label": "contract ICollateralManager", + "numberOfBytes": "20" + }, + "t_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_contract(IEscrowVault)48831": { + "label": "contract IEscrowVault", + "numberOfBytes": "20" + }, + "t_contract(ILenderManager)49339": { + "label": "contract ILenderManager", + "numberOfBytes": "20" + }, + "t_contract(IMarketRegistry)49610": { + "label": "contract IMarketRegistry", + "numberOfBytes": "20" + }, + "t_contract(IReputationManager)49705": { + "label": "contract IReputationManager", + "numberOfBytes": "20" + }, + "t_enum(BidState)44620": { + "label": "enum BidState", + "members": [ + "NONEXISTENT", + "PENDING", + "CANCELLED", + "ACCEPTED", + "PAID", + "LIQUIDATED", + "CLOSED" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentCycleType)54768": { + "label": "enum PaymentCycleType", + "members": [ + "Seconds", + "Monthly" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentType)54765": { + "label": "enum PaymentType", + "members": [ + "EMI", + "Bullet" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_array(t_uint256)dyn_storage)": { + "label": "mapping(address => uint256[])", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_struct(AddressSet)13999_storage)": { + "label": "mapping(address => struct EnumerableSet.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_struct(UintSet)14156_storage)": { + "label": "mapping(address => struct EnumerableSet.UintSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_enum(PaymentCycleType)54768)": { + "label": "mapping(uint256 => enum PaymentCycleType)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_string_storage)": { + "label": "mapping(uint256 => string)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Bid)44648_storage)": { + "label": "mapping(uint256 => struct Bid)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint32)": { + "label": "mapping(uint256 => uint32)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)13999_storage": { + "label": "struct EnumerableSet.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Bid)44648_storage": { + "label": "struct Bid", + "members": [ + { + "label": "borrower", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "receiver", + "type": "t_address", + "offset": 0, + "slot": "1" + }, + { + "label": "lender", + "type": "t_address", + "offset": 0, + "slot": "2" + }, + { + "label": "marketplaceId", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "_metadataURI", + "type": "t_bytes32", + "offset": 0, + "slot": "4" + }, + { + "label": "loanDetails", + "type": "t_struct(LoanDetails)44665_storage", + "offset": 0, + "slot": "5" + }, + { + "label": "terms", + "type": "t_struct(Terms)44672_storage", + "offset": 0, + "slot": "10" + }, + { + "label": "state", + "type": "t_enum(BidState)44620", + "offset": 0, + "slot": "12" + }, + { + "label": "paymentType", + "type": "t_enum(PaymentType)54765", + "offset": 1, + "slot": "12" + } + ], + "numberOfBytes": "416" + }, + "t_struct(LoanDetails)44665_storage": { + "label": "struct LoanDetails", + "members": [ + { + "label": "lendingToken", + "type": "t_contract(IERC20)8314", + "offset": 0, + "slot": "0" + }, + { + "label": "principal", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "totalRepaid", + "type": "t_struct(Payment)44625_storage", + "offset": 0, + "slot": "2" + }, + { + "label": "timestamp", + "type": "t_uint32", + "offset": 0, + "slot": "4" + }, + { + "label": "acceptedTimestamp", + "type": "t_uint32", + "offset": 4, + "slot": "4" + }, + { + "label": "lastRepaidTimestamp", + "type": "t_uint32", + "offset": 8, + "slot": "4" + }, + { + "label": "loanDuration", + "type": "t_uint32", + "offset": 12, + "slot": "4" + } + ], + "numberOfBytes": "160" + }, + "t_struct(Payment)44625_storage": { + "label": "struct Payment", + "members": [ + { + "label": "principal", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "interest", + "type": "t_uint256", + "offset": 0, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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_struct(Terms)44672_storage": { + "label": "struct Terms", + "members": [ + { + "label": "paymentCycleAmount", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "paymentCycle", + "type": "t_uint32", + "offset": 0, + "slot": "1" + }, + { + "label": "APR", + "type": "t_uint16", + "offset": 4, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_struct(UintSet)14156_storage": { + "label": "struct EnumerableSet.UintSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "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": {} + } + }, + "0d4a31f6f624b9c75868f8aea57e4c032618e937096f23cbd615456f3839a1e1": { + "address": "0xf7B14778035fEAF44540A0bC1D4ED859bCB28229", + "txHash": "0x060c6857f298204d6f8b9b9f76111625070f5f87a2317f4fc65b8d8f7b6f262f", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "tellerV2", + "offset": 0, + "slot": "101", + "type": "t_contract(ITellerV2)50063", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:24" + }, + { + "label": "collateralEscrowBeacon", + "offset": 0, + "slot": "102", + "type": "t_address", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:25" + }, + { + "label": "_escrows", + "offset": 0, + "slot": "103", + "type": "t_mapping(t_uint256,t_address)", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:28" + }, + { + "label": "_bidCollaterals", + "offset": 0, + "slot": "104", + "type": "t_mapping(t_uint256,t_struct(CollateralInfo)14335_storage)", + "contract": "CollateralManager", + "src": "contracts/CollateralManager.sol:30" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "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_contract(ITellerV2)50063": { + "label": "contract ITellerV2", + "numberOfBytes": "20" + }, + "t_enum(CollateralType)51757": { + "label": "enum CollateralType", + "members": [ + "ERC20", + "ERC721", + "ERC1155" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_struct(Collateral)51767_storage)": { + "label": "mapping(address => struct Collateral)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(CollateralInfo)14335_storage)": { + "label": "mapping(uint256 => struct CollateralManager.CollateralInfo)", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)5821_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)5506_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Collateral)51767_storage": { + "label": "struct Collateral", + "members": [ + { + "label": "_collateralType", + "type": "t_enum(CollateralType)51757", + "offset": 0, + "slot": "0" + }, + { + "label": "_amount", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "_tokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "_collateralAddress", + "type": "t_address", + "offset": 0, + "slot": "3" + } + ], + "numberOfBytes": "128" + }, + "t_struct(CollateralInfo)14335_storage": { + "label": "struct CollateralManager.CollateralInfo", + "members": [ + { + "label": "collateralAddresses", + "type": "t_struct(AddressSet)5821_storage", + "offset": 0, + "slot": "0" + }, + { + "label": "collateralInfo", + "type": "t_mapping(t_address,t_struct(Collateral)51767_storage)", + "offset": 0, + "slot": "2" + } + ], + "numberOfBytes": "96" + }, + "t_struct(Set)5506_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_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "3da6928b9090457692f910cf04bdd97c5a502e94c34c623e931d0082a9e15f58": { + "address": "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f", + "txHash": "0x2835b7c1f2da3e9c5f3b7c563513eb0e4b926db624ac775ccf7823cca2328ca9", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "balances", + "offset": 0, + "slot": "51", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "EscrowVault", + "src": "contracts/EscrowVault.sol:21" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)50_storage": { + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "80889dce3a01abff40361826aa8e12a56254a298b2db1bc457492a6524584da3": { + "address": "0x0D1047229B9851eACE463Fb25f27982a5127c20F", + "txHash": "0x16c72932ed85b94fb9f400349f9021eb65ec845f30983fb11f93271ef04632ae", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" + }, + { + "label": "lenderAttestationSchemaId", + "offset": 0, + "slot": "1", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:52" + }, + { + "label": "markets", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_uint256,t_struct(Marketplace)38479_storage)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:54" + }, + { + "label": "__uriToId", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_bytes32,t_uint256)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:55" + }, + { + "label": "marketCount", + "offset": 0, + "slot": "4", + "type": "t_uint256", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:56" + }, + { + "label": "_attestingSchemaId", + "offset": 0, + "slot": "5", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:57" + }, + { + "label": "borrowerAttestationSchemaId", + "offset": 0, + "slot": "6", + "type": "t_bytes32", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:58" + }, + { + "label": "version", + "offset": 0, + "slot": "7", + "type": "t_uint256", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:60" + }, + { + "label": "marketIsClosed", + "offset": 0, + "slot": "8", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:62" + }, + { + "label": "tellerAS", + "offset": 0, + "slot": "9", + "type": "t_contract(TellerAS)16551", + "contract": "MarketRegistry", + "src": "contracts/MarketRegistry.sol:64" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(TellerAS)16551": { + "label": "contract TellerAS", + "numberOfBytes": "20" + }, + "t_enum(PaymentCycleType)54768": { + "label": "enum PaymentCycleType", + "members": [ + "Seconds", + "Monthly" + ], + "numberOfBytes": "1" + }, + "t_enum(PaymentType)54765": { + "label": "enum PaymentType", + "members": [ + "EMI", + "Bullet" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_bytes32)": { + "label": "mapping(address => bytes32)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Marketplace)38479_storage)": { + "label": "mapping(uint256 => struct MarketRegistry.Marketplace)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)13999_storage": { + "label": "struct EnumerableSet.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Marketplace)38479_storage": { + "label": "struct MarketRegistry.Marketplace", + "members": [ + { + "label": "owner", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "metadataURI", + "type": "t_string_storage", + "offset": 0, + "slot": "1" + }, + { + "label": "marketplaceFeePercent", + "type": "t_uint16", + "offset": 0, + "slot": "2" + }, + { + "label": "lenderAttestationRequired", + "type": "t_bool", + "offset": 2, + "slot": "2" + }, + { + "label": "verifiedLendersForMarket", + "type": "t_struct(AddressSet)13999_storage", + "offset": 0, + "slot": "3" + }, + { + "label": "lenderAttestationIds", + "type": "t_mapping(t_address,t_bytes32)", + "offset": 0, + "slot": "5" + }, + { + "label": "paymentCycleDuration", + "type": "t_uint32", + "offset": 0, + "slot": "6" + }, + { + "label": "paymentDefaultDuration", + "type": "t_uint32", + "offset": 4, + "slot": "6" + }, + { + "label": "bidExpirationTime", + "type": "t_uint32", + "offset": 8, + "slot": "6" + }, + { + "label": "borrowerAttestationRequired", + "type": "t_bool", + "offset": 12, + "slot": "6" + }, + { + "label": "verifiedBorrowersForMarket", + "type": "t_struct(AddressSet)13999_storage", + "offset": 0, + "slot": "7" + }, + { + "label": "borrowerAttestationIds", + "type": "t_mapping(t_address,t_bytes32)", + "offset": 0, + "slot": "9" + }, + { + "label": "feeRecipient", + "type": "t_address", + "offset": 0, + "slot": "10" + }, + { + "label": "paymentType", + "type": "t_enum(PaymentType)54765", + "offset": 20, + "slot": "10" + }, + { + "label": "paymentCycleType", + "type": "t_enum(PaymentCycleType)54768", + "offset": 21, + "slot": "10" + } + ], + "numberOfBytes": "352" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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": {} + } + }, + "2d511ca65dc43e30f894c3588bc5bff877cc3e7d03d8e8c5785ae6e9057c32d0": { + "address": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b", + "txHash": "0x48348141dc787a47d9a4ee0986958e1cf2c313d28c1e6cf9dbad2c13b750182a", + "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)49060_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:53" + }, + { + "label": "commitmentCount", + "offset": 0, + "slot": "152", + "type": "t_uint256", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:55" + }, + { + "label": "commitmentBorrowersList", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_struct(AddressSet)5821_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:58" + }, + { + "label": "commitmentPrincipalAccepted", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:62" + }, + { + "label": "commitmentUniswapPoolRoutes", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)49071_storage)dyn_storage)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:64" + }, + { + "label": "commitmentPoolOracleLtvRatio", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_uint256,t_uint16)", + "contract": "LenderCommitmentForwarder_U1", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U1.sol:66" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(PoolRouteConfig)49071_storage)dyn_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)49036": { + "label": "enum ILenderCommitmentForwarder_U1.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)49071_storage)dyn_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.PoolRouteConfig[])", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(AddressSet)5821_storage)": { + "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Commitment)49060_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U1.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)5821_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)5506_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Commitment)49060_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)49036", + "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)49071_storage": { + "label": "struct ILenderCommitmentForwarder_U1.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)5506_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": {} + } + }, + "4e0bb7b34c3abb5c63a1be73b775bb5e432518c21fb0f98e1b0858f169b3a2b1": { + "address": "0x0b65C94CfF84afa6D9CE3D287b1227D9Cc7CdfB7", + "txHash": "0x733f49d10f692e9547468125c693ef917b7f6b880cebbf32e99062fac33ea3dd", + "layout": { + "solcVersion": "0.8.11", + "storage": [], + "types": {}, + "namespaces": {} + } + }, + "6844b181a7d9e56a478a6c2bdabdbc91989abafcf4aa4ccf82e048364fee21a5": { + "address": "0xfCd6Aa92D399260E8309800316CEc9b1F123621e", + "txHash": "0xf70db9b715e179be1bd51d545badb54f25e457b107a7149827ba7c81847975ad", + "layout": { + "solcVersion": "0.8.11", + "storage": [], + "types": {}, + "namespaces": {} + } + }, + "efa795b40bfc236128a68c937980b583d335df4626e01410ee2029ee47e7b055": { + "address": "0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB", + "txHash": "0x40717a2a3515969f853ac88c687faa02b0371073429206638deeeb2f2a6a8f5e", + "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": "__gap", + "offset": 0, + "slot": "151", + "type": "t_array(t_uint256)50_storage", + "contract": "TellerV2MarketForwarder_G3", + "src": "contracts/TellerV2MarketForwarder_G3.sol:59" + }, + { + "label": "_paused", + "offset": 0, + "slot": "201", + "type": "t_bool", + "contract": "PausableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:29" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)49_storage", + "contract": "PausableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol:116" + }, + { + "label": "_status", + "offset": 0, + "slot": "251", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "252", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_owner", + "offset": 0, + "slot": "301", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "302", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "liquidationProtocolFeePercent", + "offset": 0, + "slot": "351", + "type": "t_uint256", + "contract": "SmartCommitmentForwarder", + "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:88" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "352", + "type": "t_uint256", + "contract": "SmartCommitmentForwarder", + "src": "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol:89" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_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_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "59da181c273f4bd03bec57e2a33af721cf9fc478e2768226374c7b64bc04676a": { + "address": "0x7292385522F11390B2A7dd4677528fFce03b80db", + "txHash": "0x46dbf2c4d17e54c423bbebce959161737b5277d43bfa084c769311761909fe8c", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts/proxy/utils/Initializable.sol:67" + }, + { + "label": "tellerV2", + "offset": 2, + "slot": "0", + "type": "t_contract(ITellerV2)50063", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:17" + }, + { + "label": "_delinquencies", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:18" + }, + { + "label": "_defaults", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:19" + }, + { + "label": "_currentDelinquencies", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:20" + }, + { + "label": "_currentDefaults", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_address,t_struct(UintSet)14156_storage)", + "contract": "ReputationManager", + "src": "contracts/ReputationManager.sol:21" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_contract(ITellerV2)50063": { + "label": "contract ITellerV2", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_struct(UintSet)14156_storage)": { + "label": "mapping(address => struct EnumerableSet.UintSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_struct(Set)13684_storage": { + "label": "struct EnumerableSet.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_struct(UintSet)14156_storage": { + "label": "struct EnumerableSet.UintSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)13684_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "f3c0cf34a7ad4bc181ecefd623fc1a0900c964d440e8a140939cf03b6acf7e3b": { + "address": "0xb7695470E9c8d6E84F4786C240960B7822106b63", + "txHash": "0x91154742f2b45d2ef3346c9aea10548d42ce975e0e9619fc186cfd007472ea95", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "__gap", + "offset": 0, + "slot": "101", + "type": "t_array(t_uint256)50_storage", + "contract": "ERC165Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "151", + "type": "t_string_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:25" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "152", + "type": "t_string_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:28" + }, + { + "label": "_owners", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_address)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:31" + }, + { + "label": "_balances", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:34" + }, + { + "label": "_tokenApprovals", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_address)", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:37" + }, + { + "label": "_operatorApprovals", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:40" + }, + { + "label": "__gap", + "offset": 0, + "slot": "157", + "type": "t_array(t_uint256)44_storage", + "contract": "ERC721Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol:514" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)44_storage": { + "label": "uint256[44]", + "numberOfBytes": "1408" + }, + "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_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_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_address)": { + "label": "mapping(uint256 => address)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "c8d7b90093e71c94d09f4e272108089f270011c5e03a0bf523ee49820a9ed773": { + "address": "0x13a5735F356B4ede9D3F65D3eDdb62651df1cC37", + "txHash": "0xf6a01570bf95ed26dd3b1ef3e35bb8c89181f257995e75384c111a466b765e03", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_protocolPaused", + "offset": 0, + "slot": "101", + "type": "t_bool", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:23" + }, + { + "label": "_liquidationsPaused", + "offset": 1, + "slot": "101", + "type": "t_bool", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:24" + }, + { + "label": "pauserRoleBearer", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_bool)", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:26" + }, + { + "label": "lastPausedAt", + "offset": 0, + "slot": "103", + "type": "t_uint256", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:29" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "104", + "type": "t_uint256", + "contract": "ProtocolPausingManager", + "src": "contracts/pausing/ProtocolPausingManager.sol:30" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "da0219be65e3c43c65d98445d10cb3b8d0f5dfa56f4e2246c232b6274c2ca566": { + "address": "0xf6E926D7282Ba2Dc1bd580dA36420d2067bEc4A3", + "txHash": "0xee4617757c8f9015c043c99f65db914def49b8acb502794121cf015c76e6fad4", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_status", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" + }, + { + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" + }, + { + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" + }, + { + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" + }, + { + "label": "poolSharesLastTransferredAt", + "offset": 0, + "slot": "201", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)50_storage", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" + }, + { + "label": "principalToken", + "offset": 0, + "slot": "252", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:119" + }, + { + "label": "collateralToken", + "offset": 0, + "slot": "253", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:120" + }, + { + "label": "marketId", + "offset": 0, + "slot": "254", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:122" + }, + { + "label": "totalPrincipalTokensCommitted", + "offset": 0, + "slot": "255", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:125" + }, + { + "label": "totalPrincipalTokensWithdrawn", + "offset": 0, + "slot": "256", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:126" + }, + { + "label": "totalPrincipalTokensLended", + "offset": 0, + "slot": "257", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:128" + }, + { + "label": "totalPrincipalTokensRepaid", + "offset": 0, + "slot": "258", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:129" + }, + { + "label": "excessivePrincipalTokensRepaid", + "offset": 0, + "slot": "259", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:130" + }, + { + "label": "totalInterestCollected", + "offset": 0, + "slot": "260", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:132" + }, + { + "label": "liquidityThresholdPercent", + "offset": 0, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:134" + }, + { + "label": "collateralRatio", + "offset": 2, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:135" + }, + { + "label": "maxLoanDuration", + "offset": 4, + "slot": "261", + "type": "t_uint32", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:137" + }, + { + "label": "interestRateLowerBound", + "offset": 8, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:138" + }, + { + "label": "interestRateUpperBound", + "offset": 10, + "slot": "261", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:139" + }, + { + "label": "activeBids", + "offset": 0, + "slot": "262", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:147" + }, + { + "label": "activeBidsAmountDueRemaining", + "offset": 0, + "slot": "263", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:148" + }, + { + "label": "tokenDifferenceFromLiquidations", + "offset": 0, + "slot": "264", + "type": "t_int256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:150" + }, + { + "label": "firstDepositMade_deprecated", + "offset": 0, + "slot": "265", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:152" + }, + { + "label": "withdrawDelayTimeSeconds", + "offset": 0, + "slot": "266", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:153" + }, + { + "label": "poolOracleRoutes", + "offset": 0, + "slot": "267", + "type": "t_array(t_struct(PoolRouteConfig)50152_storage)dyn_storage", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:155" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "offset": 0, + "slot": "268", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:158" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "269", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:161" + }, + { + "label": "paused", + "offset": 0, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:162" + }, + { + "label": "borrowingPaused", + "offset": 1, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:163" + }, + { + "label": "liquidationAuctionPaused", + "offset": 2, + "slot": "270", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:164" + }, + { + "label": "withdrawDelayBypassForAccount", + "offset": 0, + "slot": "271", + "type": "t_mapping(t_address,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.sol:166" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_struct(PoolRouteConfig)50152_storage)dyn_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", + "numberOfBytes": "32" + }, + "t_array(t_uint256)45_storage": { + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "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_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_int256": { + "label": "int256", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(PoolRouteConfig)50152_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_uint16": { + "label": "uint16", + "numberOfBytes": "2" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint32": { + "label": "uint32", + "numberOfBytes": "4" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "6f01541265576f4854242ff526c30b4e304ae07d7b0c03a7210326a561fea83e": { + "address": "0x437b82f48Cd7E60742C87f4DF45eCf13B6CA935c", + "txHash": "0xe1e90fd8b7fb0c962586573b6d3926bbea1754b36864fb38aa424e219785f39d", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "lenderGroupBeacon", + "offset": 0, + "slot": "101", + "type": "t_address", + "contract": "LenderCommitmentGroupFactory_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:32" + }, + { + "label": "deployedLenderGroupContracts", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupFactory_V2", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol:36" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "575bdc232a98700560b39afca71448fd5ea24bcf976cb88adef58e94c6b2839f": { + "address": "0x5360af9B95701504F783d8654bA02B0AF5155f64", + "txHash": "0x35d23fcfb98b8ad58f99cde93c8b0ec0cb34536be0f7f9ccd10789a9a4638373", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "allocationCount", + "offset": 0, + "slot": "1", + "type": "t_uint256", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:31" + }, + { + "label": "allocatedRewards", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_uint256,t_struct(RewardAllocation)49396_storage)", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:34" + }, + { + "label": "rewardClaimedForBid", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))", + "contract": "MarketLiquidityRewards", + "src": "contracts/MarketLiquidityRewards.sol:37" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_enum(AllocationStrategy)49399": { + "label": "enum IMarketLiquidityRewards.AllocationStrategy", + "members": [ + "BORROWER", + "LENDER" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_mapping(t_uint256,t_bool))": { + "label": "mapping(uint256 => mapping(uint256 => bool))", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(RewardAllocation)49396_storage)": { + "label": "mapping(uint256 => struct IMarketLiquidityRewards.RewardAllocation)", + "numberOfBytes": "32" + }, + "t_struct(RewardAllocation)49396_storage": { + "label": "struct IMarketLiquidityRewards.RewardAllocation", + "members": [ + { + "label": "allocator", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "rewardTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "1" + }, + { + "label": "rewardTokenAmount", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "marketId", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "requiredPrincipalTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "4" + }, + { + "label": "requiredCollateralTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "5" + }, + { + "label": "minimumCollateralPerPrincipalAmount", + "type": "t_uint256", + "offset": 0, + "slot": "6" + }, + { + "label": "rewardPerLoanPrincipalAmount", + "type": "t_uint256", + "offset": 0, + "slot": "7" + }, + { + "label": "bidStartTimeMin", + "type": "t_uint32", + "offset": 0, + "slot": "8" + }, + { + "label": "bidStartTimeMax", + "type": "t_uint32", + "offset": 4, + "slot": "8" + }, + { + "label": "allocationStrategy", + "type": "t_enum(AllocationStrategy)49399", + "offset": 8, + "slot": "8" + } + ], + "numberOfBytes": "288" + }, + "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/upgrades/38_transfer_apechain_timelock_ownership.ts b/packages/contracts/deploy/upgrades/38_transfer_apechain_timelock_ownership.ts new file mode 100644 index 000000000..3c2437be9 --- /dev/null +++ b/packages/contracts/deploy/upgrades/38_transfer_apechain_timelock_ownership.ts @@ -0,0 +1,87 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' +import { logTxLink } from 'helpers/logTxLink' + +const deployFn: DeployFunction = async (hre) => { + hre.log('=================================================================') + hre.log('') + hre.log('ApeChain: Transferring beacon + proxy admin ownership to Timelock') + hre.log('') + + const { deployer, protocolTimelock } = await hre.getNamedAccounts() + + // --- Transfer beacon ownership --- + + const beaconNames = [ + 'CollateralEscrowBeacon', + 'LenderCommitmentGroupBeaconV2', + ] + + for (const beaconName of beaconNames) { + const beacon = await hre.contracts.get(beaconName) + const currentOwner = await beacon.owner() + + if (currentOwner === protocolTimelock) { + hre.log( + ` ✅ ${beaconName} ownership is already set to Timelock` + ) + } else if (currentOwner === deployer) { + hre.log(` Transferring ${beaconName} ownership to Timelock...`) + const tx = await beacon.transferOwnership(protocolTimelock) + await tx.wait(1) + hre.log( + ` ✅ ${beaconName} ownership transferred to Timelock (${protocolTimelock})` + ) + await logTxLink(hre, tx.hash) + } else { + hre.log( + ` ⚠️ ${beaconName} is owned by ${currentOwner} (not deployer). Skipping.` + ) + } + } + + // --- Transfer Default Proxy Admin ownership --- + + hre.log('') + hre.log(' Checking Default Proxy Admin ownership...') + + const defaultProxyAdmin = await hre.upgrades.admin.getInstance() + const proxyAdminOwner = await defaultProxyAdmin.owner() + + if (proxyAdminOwner === protocolTimelock) { + hre.log(' ✅ Default Proxy Admin ownership is already set to Timelock') + } else if (proxyAdminOwner === deployer) { + hre.log(' Transferring Default Proxy Admin ownership to Timelock...') + const signer = await hre.getNamedSigner('deployer') + await hre.upgrades.admin.transferProxyAdminOwnership( + protocolTimelock, + signer + ) + hre.log( + ` ✅ Default Proxy Admin ownership transferred to Timelock (${protocolTimelock})` + ) + } else { + hre.log( + ` ⚠️ Default Proxy Admin is owned by ${proxyAdminOwner} (not deployer). Skipping.` + ) + } + + hre.log('') + hre.log('done.') + hre.log('=================================================================') + + return true +} + +// tags and deployment +deployFn.id = 'apechain:transfer-timelock-ownership' +deployFn.tags = ['apechain', 'apechain:transfer-timelock-ownership'] +deployFn.dependencies = [ + 'collateral:escrow-beacon:deploy', + 'lender-commitment-group-beacon-v2:deploy', + 'teller-v2:deploy', +] + +deployFn.skip = async (hre) => { + return !hre.network.live || hre.network.name !== 'apechain' +} +export default deployFn diff --git a/packages/contracts/deployments/apechain/.chainId b/packages/contracts/deployments/apechain/.chainId new file mode 100644 index 000000000..5263e1b9b --- /dev/null +++ b/packages/contracts/deployments/apechain/.chainId @@ -0,0 +1 @@ +33139 \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/.latestDeploymentBlock b/packages/contracts/deployments/apechain/.latestDeploymentBlock new file mode 100644 index 000000000..e36d911b5 --- /dev/null +++ b/packages/contracts/deployments/apechain/.latestDeploymentBlock @@ -0,0 +1 @@ +33944634 \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/.migrations.json b/packages/contracts/deployments/apechain/.migrations.json new file mode 100644 index 000000000..fbbbfab64 --- /dev/null +++ b/packages/contracts/deployments/apechain/.migrations.json @@ -0,0 +1,27 @@ +{ + "timelock-controller:deploy": 1771555482, + "collateral:escrow-beacon:deploy": 1771555486, + "meta-forwarder:deploy": 1771555491, + "teller-v2:deploy": 1771555497, + "collateral:manager:deploy": 1771555500, + "escrow-vault:deploy": 1771555504, + "market-registry:deploy": 1771555515, + "lender-commitment-forwarder:alpha:deploy": 1771555519, + "lender-commitment-forwarder:extensions:borrow-swap:deploy": 1771555521, + "lender-commitment-forwarder:extensions:flash-swap-rollover:deploy": 1771555524, + "smart-commitment-forwarder:deploy": 1771555527, + "reputation-manager:deploy": 1771555533, + "lender-manager:deploy": 1771555535, + "protocol-pausing-manager:deploy": 1771555539, + "teller-v2:init": 1771555540, + "lender-commitment-group-beacon-v2:deploy": 1771555545, + "lender-commitment-group-factory-v2:deploy": 1771555550, + "teller-v2:transfer-ownership-to-safe": 1771555550, + "lender-manager:transfer-ownership": 1771555551, + "liquidity-rewards:deploy": 1771555554, + "hypernative-oracle-mock:deploy": 1771555556, + "apechain:transfer-ownership-to-safe": 1771555559, + "validate-deployments": 1771555560, + "default-proxy-admin:transfer": 1771555560, + "apechain:transfer-timelock-ownership": 1771556073 +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/BorrowSwap.json b/packages/contracts/deployments/apechain/BorrowSwap.json new file mode 100644 index 000000000..f015127d1 --- /dev/null +++ b/packages/contracts/deployments/apechain/BorrowSwap.json @@ -0,0 +1,306 @@ +{ + "address": "0xa1106d888F1FA689c6935e0983687432eF2a28c1", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_swapRouter" + }, + { + "type": "address", + "name": "_quoter" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowSwapComplete", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": false + }, + { + "type": "uint256", + "name": "loanId", + "indexed": false + }, + { + "type": "address", + "name": "token0", + "indexed": false + }, + { + "type": "uint256", + "name": "amountIn", + "indexed": false + }, + { + "type": "uint256", + "name": "amountOut", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_QUOTER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_SWAP_ROUTER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowSwap", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "address", + "name": "_principalToken" + }, + { + "type": "uint256", + "name": "_additionalInputAmount" + }, + { + "type": "tuple", + "name": "_swapArgs", + "components": [ + { + "type": "tuple[]", + "name": "swapPaths", + "components": [ + { + "type": "uint24", + "name": "poolFee" + }, + { + "type": "address", + "name": "tokenOut" + } + ] + }, + { + "type": "uint160", + "name": "amountOutMinimum" + } + ] + }, + { + "type": "tuple", + "name": "_acceptCommitmentArgs", + "components": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "address", + "name": "smartCommitmentAddress" + }, + { + "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": "function", + "name": "generateSwapPath", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "inputToken" + }, + { + "type": "tuple[]", + "name": "swapPaths", + "components": [ + { + "type": "uint24", + "name": "poolFee" + }, + { + "type": "address", + "name": "tokenOut" + } + ] + } + ], + "outputs": [ + { + "type": "bytes", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketFeePct", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketIdForCommitment", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "quoteExactInput", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "inputToken" + }, + { + "type": "uint256", + "name": "amountIn" + }, + { + "type": "tuple[]", + "name": "swapPaths", + "components": [ + { + "type": "uint24", + "name": "poolFee" + }, + { + "type": "address", + "name": "tokenOut" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "amountOut" + } + ] + } + ], + "transactionHash": "0x719c72815d86034751e0d219c8731e7cf62d21a979c246a6e62a4a46485378c2", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0xd2ddb1644575616747f6dbd26c2b2d30b7f1c164c805d6f9ffd5ca044f528a3d", + "blockNumber": 33944595 + }, + "numDeployments": 1, + "implementation": "0x0b65C94CfF84afa6D9CE3D287b1227D9Cc7CdfB7" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/CollateralEscrowBeacon.json b/packages/contracts/deployments/apechain/CollateralEscrowBeacon.json new file mode 100644 index 000000000..e4e9e58cd --- /dev/null +++ b/packages/contracts/deployments/apechain/CollateralEscrowBeacon.json @@ -0,0 +1,350 @@ +{ + "address": "0xBf4E3fEA276057D0b26f52141557C835a7E2d534", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "CollateralDeposited", + "inputs": [ + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralWithdrawn", + "inputs": [ + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "address", + "name": "_recipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "bidId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralBalances", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + }, + { + "type": "function", + "name": "depositAsset", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "address", + "name": "_collateralAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "onERC1155BatchReceived", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256[]", + "name": "_ids" + }, + { + "type": "uint256[]", + "name": "_values" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC1155Received", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "id" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC721Received", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdrawDustTokens", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "tokenAddress" + }, + { + "type": "uint256", + "name": "amount" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0xfA87381128aAF95fB637BbA0B760bA2f9970c2b5" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/CollateralManager.json b/packages/contracts/deployments/apechain/CollateralManager.json new file mode 100644 index 000000000..15f0e541d --- /dev/null +++ b/packages/contracts/deployments/apechain/CollateralManager.json @@ -0,0 +1,721 @@ +{ + "address": "0x90D08f8Df66dFdE93801783FF7A36876453DAE75", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "CollateralClaimed", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralCommitted", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralDeposited", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralEscrowDeployed", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "address", + "name": "_collateralEscrow", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CollateralWithdrawn", + "inputs": [ + { + "type": "uint256", + "name": "_bidId", + "indexed": false + }, + { + "type": "uint8", + "name": "_type", + "indexed": false + }, + { + "type": "address", + "name": "_collateralAddress", + "indexed": false + }, + { + "type": "uint256", + "name": "_amount", + "indexed": false + }, + { + "type": "uint256", + "name": "_tokenId", + "indexed": false + }, + { + "type": "address", + "name": "_recipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "_escrows", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "checkBalances", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validated_" + }, + { + "type": "bool[]", + "name": "checks_" + } + ] + }, + { + "type": "function", + "name": "commitCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "commitCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "tuple", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "deployAndDeposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "amount_" + } + ] + }, + { + "type": "function", + "name": "getCollateralEscrowBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralInfo", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "tuple[]", + "name": "infos_", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ] + }, + { + "type": "function", + "name": "getEscrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralEscrowBeacon" + }, + { + "type": "address", + "name": "_tellerV2" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isBidCollateralBacked", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderClaimCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderClaimCollateralWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralRecipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidateCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_liquidatorAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "onERC1155BatchReceived", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256[]", + "name": "_ids" + }, + { + "type": "uint256[]", + "name": "_values" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC1155Received", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "id" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "onERC721Received", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ], + "outputs": [ + { + "type": "bytes4", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "revalidateCollateral", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "validation_" + } + ] + }, + { + "type": "function", + "name": "setCollateralEscrowBeacon", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_collateralEscrowBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "withdrawDustTokens", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_tokenAddress" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "address", + "name": "_recipientAddress" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x145f1c9d10a249546f02bb8b7c779e8bba95c12d4de601bf7151d7d7dae11d62", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x8e8bf93d4e6df659dd6054ebd9a72f60a11ed3a4f8d790e35e65d98325e8c20f", + "blockNumber": 33944575 + }, + "numDeployments": 1, + "implementation": "0xf7B14778035fEAF44540A0bC1D4ED859bCB28229" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/EscrowVault.json b/packages/contracts/deployments/apechain/EscrowVault.json new file mode 100644 index 000000000..b12801dd5 --- /dev/null +++ b/packages/contracts/deployments/apechain/EscrowVault.json @@ -0,0 +1,101 @@ +{ + "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "balances", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + }, + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x52c6eb9126c15ee75517d01db512f72b042b23b0b3392f1f3af93ea4719735bd", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x66297203779a2d9cd47381166e2000528d4f71bdf916580ac9742f614e8ff69f", + "blockNumber": 33944578 + }, + "numDeployments": 1, + "implementation": "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/HypernativeOracle.json b/packages/contracts/deployments/apechain/HypernativeOracle.json new file mode 100644 index 000000000..feb626fe1 --- /dev/null +++ b/packages/contracts/deployments/apechain/HypernativeOracle.json @@ -0,0 +1,737 @@ +{ + "address": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "abi": [ + { + "inputs": [ + { + "internalType": "address", + "name": "_admin", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Allowed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Blacklisted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + } + ], + "name": "ConsumerAdded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + } + ], + "name": "ConsumerRemoved", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "consumer", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Registered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "previousAdminRole", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "newAdminRole", + "type": "bytes32" + } + ], + "name": "RoleAdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleGranted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleRevoked", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "threshold", + "type": "uint256" + } + ], + "name": "TimeThresholdChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "Whitelisted", + "type": "event" + }, + { + "inputs": [], + "name": "CONSUMER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DEFAULT_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "OPERATOR_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "consumers", + "type": "address[]" + } + ], + "name": "addConsumers", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "operator", + "type": "address" + } + ], + "name": "addOperator", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "allow", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "blacklist", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_newThreshold", + "type": "uint256" + } + ], + "name": "changeTimeThreshold", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + } + ], + "name": "getRoleAdmin", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "grantRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "hasRole", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "isBlacklistedAccount", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_origin", + "type": "address" + }, + { + "internalType": "address", + "name": "_sender", + "type": "address" + } + ], + "name": "isBlacklistedContext", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "isTimeExceeded", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "register", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_account", + "type": "address" + } + ], + "name": "registerStrict", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "renounceRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "consumers", + "type": "address[]" + } + ], + "name": "revokeConsumers", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "revokeRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes4", + "name": "interfaceId", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32[]", + "name": "hashedAccounts", + "type": "bytes32[]" + } + ], + "name": "whitelist", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x594427df154b7fa7d35b19d7ba1302a6dc8f8ceedc836b9b161b2809fe54d47b", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "transactionIndex": 1, + "gasUsed": "1370061", + "logsBloom": "0x00000044000000000002000040000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000020000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000200000000000000000000000000000000000000100000000000020000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xb1bdaf9489934d4ce5f937b219e87e0ecbe60409600e8af13633d72d2c0626da", + "transactionHash": "0x594427df154b7fa7d35b19d7ba1302a6dc8f8ceedc836b9b161b2809fe54d47b", + "logs": [ + { + "transactionIndex": 1, + "blockNumber": 33944634, + "transactionHash": "0x594427df154b7fa7d35b19d7ba1302a6dc8f8ceedc836b9b161b2809fe54d47b", + "address": "0xa77517dA5986793C9FAd1638212DbE05E9f5f0c5", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 0, + "blockHash": "0xb1bdaf9489934d4ce5f937b219e87e0ecbe60409600e8af13633d72d2c0626da" + } + ], + "blockNumber": 33944634, + "cumulativeGasUsed": "1370061", + "status": 1, + "byzantium": true + }, + "args": [ + "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_admin\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Allowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Blacklisted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"}],\"name\":\"ConsumerAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"}],\"name\":\"ConsumerRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"consumer\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Registered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"threshold\",\"type\":\"uint256\"}],\"name\":\"TimeThresholdChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"Whitelisted\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CONSUMER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OPERATOR_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"consumers\",\"type\":\"address[]\"}],\"name\":\"addConsumers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"addOperator\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"allow\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"blacklist\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_newThreshold\",\"type\":\"uint256\"}],\"name\":\"changeTimeThreshold\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"isBlacklistedAccount\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_origin\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_sender\",\"type\":\"address\"}],\"name\":\"isBlacklistedContext\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"isTimeExceeded\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"register\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_account\",\"type\":\"address\"}],\"name\":\"registerStrict\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"consumers\",\"type\":\"address[]\"}],\"name\":\"revokeConsumers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"revokeOperator\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"hashedAccounts\",\"type\":\"bytes32[]\"}],\"name\":\"whitelist\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"changeTimeThreshold(uint256)\":{\"details\":\"Admin only function, can be used to block any interaction with the protocol, meassured in seconds\"},\"getRoleAdmin(bytes32)\":{\"details\":\"Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}.\"},\"grantRole(bytes32,address)\":{\"details\":\"Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event.\"},\"hasRole(bytes32,address)\":{\"details\":\"Returns `true` if `account` has been granted `role`.\"},\"renounceRole(bytes32,address)\":{\"details\":\"Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event.\"},\"revokeRole(bytes32,address)\":{\"details\":\"Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event.\"},\"supportsInterface(bytes4)\":{\"details\":\"See {IERC165-supportsInterface}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/oracleprotection/HypernativeOracle.sol\":\"HypernativeOracle\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts/access/AccessControl.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IAccessControl.sol\\\";\\nimport \\\"../utils/Context.sol\\\";\\nimport \\\"../utils/Strings.sol\\\";\\nimport \\\"../utils/introspection/ERC165.sol\\\";\\n\\n/**\\n * @dev Contract module that allows children to implement role-based access\\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\\n * members except through off-chain means by accessing the contract event logs. Some\\n * applications may benefit from on-chain enumerability, for those cases see\\n * {AccessControlEnumerable}.\\n *\\n * Roles are referred to by their `bytes32` identifier. These should be exposed\\n * in the external API and be unique. The best way to achieve this is by\\n * using `public constant` hash digests:\\n *\\n * ```\\n * bytes32 public constant MY_ROLE = keccak256(\\\"MY_ROLE\\\");\\n * ```\\n *\\n * Roles can be used to represent a set of permissions. To restrict access to a\\n * function call, use {hasRole}:\\n *\\n * ```\\n * function foo() public {\\n * require(hasRole(MY_ROLE, msg.sender));\\n * ...\\n * }\\n * ```\\n *\\n * Roles can be granted and revoked dynamically via the {grantRole} and\\n * {revokeRole} functions. Each role has an associated admin role, and only\\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\\n *\\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\\n * that only accounts with this role will be able to grant or revoke other\\n * roles. More complex role relationships can be created by using\\n * {_setRoleAdmin}.\\n *\\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\\n * grant and revoke this role. Extra precautions should be taken to secure\\n * accounts that have been granted it.\\n */\\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\\n struct RoleData {\\n mapping(address => bool) members;\\n bytes32 adminRole;\\n }\\n\\n mapping(bytes32 => RoleData) private _roles;\\n\\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\\n\\n /**\\n * @dev Modifier that checks that an account has a specific role. Reverts\\n * with a standardized message including the required role.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n *\\n * _Available since v4.1._\\n */\\n modifier onlyRole(bytes32 role) {\\n _checkRole(role);\\n _;\\n }\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\\n return _roles[role].members[account];\\n }\\n\\n /**\\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\\n * Overriding this function changes the behavior of the {onlyRole} modifier.\\n *\\n * Format of the revert message is described in {_checkRole}.\\n *\\n * _Available since v4.6._\\n */\\n function _checkRole(bytes32 role) internal view virtual {\\n _checkRole(role, _msgSender());\\n }\\n\\n /**\\n * @dev Revert with a standard message if `account` is missing `role`.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n */\\n function _checkRole(bytes32 role, address account) internal view virtual {\\n if (!hasRole(role, account)) {\\n revert(\\n string(\\n abi.encodePacked(\\n \\\"AccessControl: account \\\",\\n Strings.toHexString(account),\\n \\\" is missing role \\\",\\n Strings.toHexString(uint256(role), 32)\\n )\\n )\\n );\\n }\\n }\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\\n return _roles[role].adminRole;\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function renounceRole(bytes32 role, address account) public virtual override {\\n require(account == _msgSender(), \\\"AccessControl: can only renounce roles for self\\\");\\n\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event. Note that unlike {grantRole}, this function doesn't perform any\\n * checks on the calling account.\\n *\\n * May emit a {RoleGranted} event.\\n *\\n * [WARNING]\\n * ====\\n * This function should only be called from the constructor when setting\\n * up the initial roles for the system.\\n *\\n * Using this function in any other way is effectively circumventing the admin\\n * system imposed by {AccessControl}.\\n * ====\\n *\\n * NOTE: This function is deprecated in favor of {_grantRole}.\\n */\\n function _setupRole(bytes32 role, address account) internal virtual {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Sets `adminRole` as ``role``'s admin role.\\n *\\n * Emits a {RoleAdminChanged} event.\\n */\\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\\n bytes32 previousAdminRole = getRoleAdmin(role);\\n _roles[role].adminRole = adminRole;\\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function _grantRole(bytes32 role, address account) internal virtual {\\n if (!hasRole(role, account)) {\\n _roles[role].members[account] = true;\\n emit RoleGranted(role, account, _msgSender());\\n }\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function _revokeRole(bytes32 role, address account) internal virtual {\\n if (hasRole(role, account)) {\\n _roles[role].members[account] = false;\\n emit RoleRevoked(role, account, _msgSender());\\n }\\n }\\n}\\n\",\"keccak256\":\"0x67e3daf189111d6d5b0464ed09cf9f0605a22c4b965a7fcecd707101faff008a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/access/IAccessControl.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev External interface of AccessControl declared to support ERC165 detection.\\n */\\ninterface IAccessControl {\\n /**\\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\\n *\\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\\n * {RoleAdminChanged} not being emitted signaling this.\\n *\\n * _Available since v3.1._\\n */\\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\\n\\n /**\\n * @dev Emitted when `account` is granted `role`.\\n *\\n * `sender` is the account that originated the contract call, an admin role\\n * bearer except when using {AccessControl-_setupRole}.\\n */\\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\\n\\n /**\\n * @dev Emitted when `account` is revoked `role`.\\n *\\n * `sender` is the account that originated the contract call:\\n * - if using `revokeRole`, it is the admin role bearer\\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\\n */\\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account) external view returns (bool);\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function grantRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function revokeRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been granted `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n */\\n function renounceRole(bytes32 role, address account) external;\\n}\\n\",\"keccak256\":\"0x59ce320a585d7e1f163cd70390a0ef2ff9cec832e2aa544293a00692465a7a57\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xe2e337e6dde9ef6b680e07338c493ebea1b5fd09b43424112868e9cc1706bca7\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xa4d1d62251f8574deb032a35fc948386a9b4de74b812d4f545a1ac120486b48a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/introspection/ERC165.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IERC165.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC165} interface.\\n *\\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\\n * for the additional interface id that will be supported. For example:\\n *\\n * ```solidity\\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\\n * }\\n * ```\\n *\\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\\n */\\nabstract contract ERC165 is IERC165 {\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n return interfaceId == type(IERC165).interfaceId;\\n }\\n}\\n\",\"keccak256\":\"0xd10975de010d89fd1c78dc5e8a9a7e7f496198085c151648f20cba166b32582b\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\\n /**\\n * @dev Returns true if this contract implements the interface defined by\\n * `interfaceId`. See the corresponding\\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\\n * to learn more about how these ids are created.\\n *\\n * This function call must use less than 30 000 gas.\\n */\\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\\n}\\n\",\"keccak256\":\"0x447a5f3ddc18419d41ff92b3773fb86471b1db25773e07f877f548918a185bf1\",\"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/oracleprotection/HypernativeOracle.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport {AccessControl} from \\\"@openzeppelin/contracts/access/AccessControl.sol\\\";\\n\\ncontract HypernativeOracle is AccessControl {\\n struct OracleRecord {\\n uint256 registrationTime;\\n bool isPotentialRisk;\\n }\\n\\n bytes32 public constant OPERATOR_ROLE = keccak256(\\\"OPERATOR_ROLE\\\");\\n bytes32 public constant CONSUMER_ROLE = keccak256(\\\"CONSUMER_ROLE\\\");\\n uint256 internal threshold = 2 minutes;\\n\\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\\n \\n event ConsumerAdded(address consumer);\\n event ConsumerRemoved(address consumer);\\n event Registered(address consumer, address account);\\n event Whitelisted(bytes32[] hashedAccounts);\\n event Allowed(bytes32[] hashedAccounts);\\n event Blacklisted(bytes32[] hashedAccounts);\\n event TimeThresholdChanged(uint256 threshold);\\n\\n modifier onlyAdmin() {\\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \\\"Hypernative Oracle error: admin required\\\");\\n _;\\n }\\n\\n modifier onlyOperator() {\\n require(hasRole(OPERATOR_ROLE, msg.sender), \\\"Hypernative Oracle error: operator required\\\");\\n _;\\n }\\n\\n modifier onlyConsumer {\\n require(hasRole(CONSUMER_ROLE, msg.sender), \\\"Hypernative Oracle error: consumer required\\\");\\n _;\\n }\\n\\n constructor(address _admin) {\\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\\n }\\n\\n function register(address _account) external onlyConsumer() {\\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \\\"Account already registered\\\");\\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\\n emit Registered(msg.sender, _account);\\n }\\n\\n function registerStrict(address _account) external onlyConsumer() {\\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \\\"Account already registered\\\");\\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\\n emit Registered(msg.sender, _account);\\n }\\n\\n // **\\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\\n }\\n emit Whitelisted(hashedAccounts);\\n }\\n\\n // **\\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\\n }\\n emit Blacklisted(hashedAccounts);\\n }\\n\\n // **\\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\\n // * @param hashedAccounts array of hashed accounts\\n // */\\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\\n for (uint256 i; i < hashedAccounts.length; i++) {\\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\\n }\\n emit Allowed(hashedAccounts);\\n }\\n\\n /**\\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\\n */\\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\\n require(_newThreshold >= 2 minutes, \\\"Threshold must be greater than 2 minutes\\\");\\n threshold = _newThreshold;\\n emit TimeThresholdChanged(threshold);\\n }\\n\\n function addConsumers(address[] memory consumers) public onlyAdmin() {\\n for (uint256 i; i < consumers.length; i++) {\\n _grantRole(CONSUMER_ROLE, consumers[i]);\\n emit ConsumerAdded(consumers[i]);\\n }\\n }\\n\\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\\n for (uint256 i; i < consumers.length; i++) {\\n _revokeRole(CONSUMER_ROLE, consumers[i]);\\n emit ConsumerRemoved(consumers[i]);\\n }\\n }\\n\\n function addOperator(address operator) public onlyAdmin() {\\n _grantRole(OPERATOR_ROLE, operator);\\n }\\n\\n function revokeOperator(address operator) public onlyAdmin() {\\n _revokeRole(OPERATOR_ROLE, operator);\\n }\\n\\n function changeAdmin(address _newAdmin) public onlyAdmin() {\\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\\n }\\n\\n //if true, the account has been registered for two minutes \\n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \\\"Account not registered\\\");\\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\\n }\\n\\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\\n }\\n\\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\\n return accountHashToRecord[hashedAccount].isPotentialRisk;\\n }\\n}\\n\",\"keccak256\":\"0x7c2eecadae47637f892b06431668c08e08c81911517b8d43ee1d814675512464\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052607860015534801561001557600080fd5b506040516200180938038062001809833981016040819052610036916100e6565b610041600082610047565b50610116565b6000828152602081815260408083206001600160a01b038516845290915290205460ff166100e2576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556100a13390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b6000602082840312156100f857600080fd5b81516001600160a01b038116811461010f57600080fd5b9392505050565b6116e380620001266000396000f3fe608060405234801561001057600080fd5b506004361061014d5760003560e01c80635fab577a116100c3578063a75413b41161007c578063a75413b4146102c1578063d547741f146102d4578063d7b8a621146102e7578063f5b541a6146102fa578063f6985cc31461030f578063fad8b32a1461032257600080fd5b80635fab577a1461025a5780636cffbed31461026d5780638f2839701461028057806391d14854146102935780639870d7fe146102a6578063a217fddf146102b957600080fd5b806330c7992c1161011557806330c7992c146101e657806336568abe146101f95780633b9f83831461020c57806342c18b831461021f5780634420e486146102325780634bc02da61461024557600080fd5b806301ffc9a7146101525780630d7b87e21461017a5780631c1efe9e1461018f578063248a9ca3146101a25780632f2ff15d146101d3575b600080fd5b61016561016036600461118d565b610335565b60405190151581526020015b60405180910390f35b61018d6101883660046111b7565b61036c565b005b61018d61019d366004611259565b61044c565b6101c56101b036600461131e565b60009081526020819052604090206001015490565b604051908152602001610171565b61018d6101e1366004611337565b610525565b61018d6101f4366004611363565b61054f565b61018d610207366004611337565b610670565b61018d61021a3660046111b7565b6106ea565b61018d61022d3660046111b7565b6107e9565b61018d610240366004611363565b6108b4565b6101c560008051602061166e83398151915281565b61018d61026836600461131e565b6109c5565b61016561027b366004611363565b610a89565b61018d61028e366004611363565b610b67565b6101656102a1366004611337565b610ba7565b61018d6102b4366004611363565b610bd0565b6101c5600081565b61018d6102cf366004611259565b610c0f565b61018d6102e2366004611337565b610ce4565b6101656102f536600461137e565b610d09565b6101c560008051602061168e83398151915281565b61016561031d366004611363565b610dd4565b61018d610330366004611363565b610e51565b60006001600160e01b03198216637965db0b60e01b148061036657506301ffc9a760e01b6001600160e01b03198316145b92915050565b61038460008051602061168e83398151915233610ba7565b6103a95760405162461bcd60e51b81526004016103a0906113a8565b60405180910390fd5b60005b8181101561040e576000600260008585858181106103cc576103cc6113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806104069061141f565b9150506103ac565b507f9e4e4c1f160b3b53eb86440bbe855c3fc2acdd15761379368f16cf58057c5568828260405161044092919061143a565b60405180910390a15050565b610457600033610ba7565b6104735760405162461bcd60e51b81526004016103a090611476565b60005b8151811015610521576104b060008051602061166e8339815191528383815181106104a3576104a36113f3565b6020026020010151610e8c565b7fe3f5ed5f263f1f01764a96edfc7d025f511ec5f7d180e8816908b78bcf74f0988282815181106104e3576104e36113f3565b602002602001015160405161050791906001600160a01b0391909116815260200190565b60405180910390a1806105198161141f565b915050610476565b5050565b60008281526020819052604090206001015461054081610ef1565b61054a8383610efb565b505050565b61056760008051602061166e83398151915233610ba7565b6105835760405162461bcd60e51b81526004016103a0906114be565b60008130604051602001610598929190611509565b60408051601f198184030181529181528151602092830120600081815260029093529120549091501561060d5760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b6000818152600260209081526040918290204281556001908101805460ff1916909117905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6001600160a01b03811633146106e05760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016103a0565b6105218282610e8c565b61070260008051602061168e83398151915233610ba7565b61071e5760405162461bcd60e51b81526004016103a0906113a8565b60005b818110156107b757600160026000858585818110610741576107416113f3565b90506020020135815260200190815260200160002060000181905550600060026000858585818110610775576107756113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806107af9061141f565b915050610721565b507f3e087f3011cfcdd221d882f74ea094cde44bd2090a2c8ef9bbbcd45162664042828260405161044092919061143a565b61080160008051602061168e83398151915233610ba7565b61081d5760405162461bcd60e51b81526004016103a0906113a8565b60005b8181101561088257600160026000858585818110610840576108406113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff021916908315150217905550808061087a9061141f565b915050610820565b507f6c2a1a20729e85f030b21b1d3838b795aca2b8bd26d4f5ad4134128bc1734222828260405161044092919061143a565b6108cc60008051602061166e83398151915233610ba7565b6108e85760405162461bcd60e51b81526004016103a0906114be565b600081306040516020016108fd929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150156109725760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b60008181526002602090815260409182902042905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6109d0600033610ba7565b6109ec5760405162461bcd60e51b81526004016103a090611476565b6078811015610a4e5760405162461bcd60e51b815260206004820152602860248201527f5468726573686f6c64206d7573742062652067726561746572207468616e2032604482015267206d696e7574657360c01b60648201526084016103a0565b60018190556040518181527f99d47da2054f02d98111bd426aeb7d28d2d2b8d77ad536b453f1b19f16fd44a39060200160405180910390a150565b6000610aa360008051602061166e83398151915233610ba7565b610abf5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610ad4929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150610b415760405162461bcd60e51b81526020600482015260166024820152751058d8dbdd5b9d081b9bdd081c9959da5cdd195c995960521b60448201526064016103a0565b600154600082815260026020526040902054610b5d9042611530565b119150505b919050565b610b72600033610ba7565b610b8e5760405162461bcd60e51b81526004016103a090611476565b610b99600082610efb565b610ba4600033610e8c565b50565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b610bdb600033610ba7565b610bf75760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e83398151915282610efb565b610c1a600033610ba7565b610c365760405162461bcd60e51b81526004016103a090611476565b60005b815181101561052157610c7360008051602061166e833981519152838381518110610c6657610c666113f3565b6020026020010151610efb565b7f28b26e7a3d20aedbc5f8f2ebf7da671c0491723a2b78f47a097b0e46dee07142828281518110610ca657610ca66113f3565b6020026020010151604051610cca91906001600160a01b0391909116815260200190565b60405180910390a180610cdc8161141f565b915050610c39565b600082815260208190526040902060010154610cff81610ef1565b61054a8383610e8c565b6000610d2360008051602061166e83398151915233610ba7565b610d3f5760405162461bcd60e51b81526004016103a0906114be565b60008330604051602001610d54929190611509565b60405160208183030381529060405280519060200120905060008330604051602001610d81929190611509565b60408051601f1981840301815291815281516020928301206000858152600290935291206001015490915060ff1680610dcb575060008181526002602052604090206001015460ff165b95945050505050565b6000610dee60008051602061166e83398151915233610ba7565b610e0a5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610e1f929190611509565b60408051808303601f1901815291815281516020928301206000908152600290925290206001015460ff169392505050565b610e5c600033610ba7565b610e785760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e833981519152825b610e968282610ba7565b15610521576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610ba48133610f7f565b610f058282610ba7565b610521576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f3b3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610f898282610ba7565b61052157610f9681610fd8565b610fa1836020610fea565b604051602001610fb2929190611577565b60408051601f198184030181529082905262461bcd60e51b82526103a0916004016115ec565b60606103666001600160a01b03831660145b60606000610ff983600261161f565b61100490600261163e565b67ffffffffffffffff81111561101c5761101c61122c565b6040519080825280601f01601f191660200182016040528015611046576020820181803683370190505b509050600360fc1b81600081518110611061576110616113f3565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611090576110906113f3565b60200101906001600160f81b031916908160001a90535060006110b484600261161f565b6110bf90600161163e565b90505b6001811115611137576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106110f3576110f36113f3565b1a60f81b828281518110611109576111096113f3565b60200101906001600160f81b031916908160001a90535060049490941c9361113081611656565b90506110c2565b5083156111865760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016103a0565b9392505050565b60006020828403121561119f57600080fd5b81356001600160e01b03198116811461118657600080fd5b600080602083850312156111ca57600080fd5b823567ffffffffffffffff808211156111e257600080fd5b818501915085601f8301126111f657600080fd5b81358181111561120557600080fd5b8660208260051b850101111561121a57600080fd5b60209290920196919550909350505050565b634e487b7160e01b600052604160045260246000fd5b80356001600160a01b0381168114610b6257600080fd5b6000602080838503121561126c57600080fd5b823567ffffffffffffffff8082111561128457600080fd5b818501915085601f83011261129857600080fd5b8135818111156112aa576112aa61122c565b8060051b604051601f19603f830116810181811085821117156112cf576112cf61122c565b6040529182528482019250838101850191888311156112ed57600080fd5b938501935b828510156113125761130385611242565b845293850193928501926112f2565b98975050505050505050565b60006020828403121561133057600080fd5b5035919050565b6000806040838503121561134a57600080fd5b8235915061135a60208401611242565b90509250929050565b60006020828403121561137557600080fd5b61118682611242565b6000806040838503121561139157600080fd5b61139a83611242565b915061135a60208401611242565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a206f706572617460408201526a1bdc881c995c5d5a5c995960aa1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060001982141561143357611433611409565b5060010190565b6020808252810182905260006001600160fb1b0383111561145a57600080fd5b8260051b80856040850137600092016040019182525092915050565b60208082526028908201527f48797065726e6174697665204f7261636c65206572726f723a2061646d696e206040820152671c995c5d5a5c995960c21b606082015260800190565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a20636f6e73756d60408201526a195c881c995c5d5a5c995960aa1b606082015260800190565b6bffffffffffffffffffffffff19606093841b811682529190921b16601482015260280190565b60008282101561154257611542611409565b500390565b60005b8381101561156257818101518382015260200161154a565b83811115611571576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516115af816017850160208801611547565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516115e0816028840160208801611547565b01602801949350505050565b602081526000825180602084015261160b816040850160208701611547565b601f01601f19169190910160400192915050565b600081600019048311821515161561163957611639611409565b500290565b6000821982111561165157611651611409565b500190565b60008161166557611665611409565b50600019019056fe9d56108290ea0bc9c5c59c3ad357dca9d1b29ed7f3ae1443bef2fa2159bdf5e897667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929a26469706673582212202209b92945b24aecf31433a99250e9597a1896fe78c53ca40e585638df2ca28c64736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061014d5760003560e01c80635fab577a116100c3578063a75413b41161007c578063a75413b4146102c1578063d547741f146102d4578063d7b8a621146102e7578063f5b541a6146102fa578063f6985cc31461030f578063fad8b32a1461032257600080fd5b80635fab577a1461025a5780636cffbed31461026d5780638f2839701461028057806391d14854146102935780639870d7fe146102a6578063a217fddf146102b957600080fd5b806330c7992c1161011557806330c7992c146101e657806336568abe146101f95780633b9f83831461020c57806342c18b831461021f5780634420e486146102325780634bc02da61461024557600080fd5b806301ffc9a7146101525780630d7b87e21461017a5780631c1efe9e1461018f578063248a9ca3146101a25780632f2ff15d146101d3575b600080fd5b61016561016036600461118d565b610335565b60405190151581526020015b60405180910390f35b61018d6101883660046111b7565b61036c565b005b61018d61019d366004611259565b61044c565b6101c56101b036600461131e565b60009081526020819052604090206001015490565b604051908152602001610171565b61018d6101e1366004611337565b610525565b61018d6101f4366004611363565b61054f565b61018d610207366004611337565b610670565b61018d61021a3660046111b7565b6106ea565b61018d61022d3660046111b7565b6107e9565b61018d610240366004611363565b6108b4565b6101c560008051602061166e83398151915281565b61018d61026836600461131e565b6109c5565b61016561027b366004611363565b610a89565b61018d61028e366004611363565b610b67565b6101656102a1366004611337565b610ba7565b61018d6102b4366004611363565b610bd0565b6101c5600081565b61018d6102cf366004611259565b610c0f565b61018d6102e2366004611337565b610ce4565b6101656102f536600461137e565b610d09565b6101c560008051602061168e83398151915281565b61016561031d366004611363565b610dd4565b61018d610330366004611363565b610e51565b60006001600160e01b03198216637965db0b60e01b148061036657506301ffc9a760e01b6001600160e01b03198316145b92915050565b61038460008051602061168e83398151915233610ba7565b6103a95760405162461bcd60e51b81526004016103a0906113a8565b60405180910390fd5b60005b8181101561040e576000600260008585858181106103cc576103cc6113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806104069061141f565b9150506103ac565b507f9e4e4c1f160b3b53eb86440bbe855c3fc2acdd15761379368f16cf58057c5568828260405161044092919061143a565b60405180910390a15050565b610457600033610ba7565b6104735760405162461bcd60e51b81526004016103a090611476565b60005b8151811015610521576104b060008051602061166e8339815191528383815181106104a3576104a36113f3565b6020026020010151610e8c565b7fe3f5ed5f263f1f01764a96edfc7d025f511ec5f7d180e8816908b78bcf74f0988282815181106104e3576104e36113f3565b602002602001015160405161050791906001600160a01b0391909116815260200190565b60405180910390a1806105198161141f565b915050610476565b5050565b60008281526020819052604090206001015461054081610ef1565b61054a8383610efb565b505050565b61056760008051602061166e83398151915233610ba7565b6105835760405162461bcd60e51b81526004016103a0906114be565b60008130604051602001610598929190611509565b60408051601f198184030181529181528151602092830120600081815260029093529120549091501561060d5760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b6000818152600260209081526040918290204281556001908101805460ff1916909117905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6001600160a01b03811633146106e05760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016103a0565b6105218282610e8c565b61070260008051602061168e83398151915233610ba7565b61071e5760405162461bcd60e51b81526004016103a0906113a8565b60005b818110156107b757600160026000858585818110610741576107416113f3565b90506020020135815260200190815260200160002060000181905550600060026000858585818110610775576107756113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff02191690831515021790555080806107af9061141f565b915050610721565b507f3e087f3011cfcdd221d882f74ea094cde44bd2090a2c8ef9bbbcd45162664042828260405161044092919061143a565b61080160008051602061168e83398151915233610ba7565b61081d5760405162461bcd60e51b81526004016103a0906113a8565b60005b8181101561088257600160026000858585818110610840576108406113f3565b90506020020135815260200190815260200160002060010160006101000a81548160ff021916908315150217905550808061087a9061141f565b915050610820565b507f6c2a1a20729e85f030b21b1d3838b795aca2b8bd26d4f5ad4134128bc1734222828260405161044092919061143a565b6108cc60008051602061166e83398151915233610ba7565b6108e85760405162461bcd60e51b81526004016103a0906114be565b600081306040516020016108fd929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150156109725760405162461bcd60e51b815260206004820152601a60248201527f4163636f756e7420616c7265616479207265676973746572656400000000000060448201526064016103a0565b60008181526002602090815260409182902042905581513381526001600160a01b038516918101919091527f0a31ee9d46a828884b81003c8498156ea6aa15b9b54bdd0ef0b533d9eba57e559101610440565b6109d0600033610ba7565b6109ec5760405162461bcd60e51b81526004016103a090611476565b6078811015610a4e5760405162461bcd60e51b815260206004820152602860248201527f5468726573686f6c64206d7573742062652067726561746572207468616e2032604482015267206d696e7574657360c01b60648201526084016103a0565b60018190556040518181527f99d47da2054f02d98111bd426aeb7d28d2d2b8d77ad536b453f1b19f16fd44a39060200160405180910390a150565b6000610aa360008051602061166e83398151915233610ba7565b610abf5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610ad4929190611509565b60408051601f19818403018152918152815160209283012060008181526002909352912054909150610b415760405162461bcd60e51b81526020600482015260166024820152751058d8dbdd5b9d081b9bdd081c9959da5cdd195c995960521b60448201526064016103a0565b600154600082815260026020526040902054610b5d9042611530565b119150505b919050565b610b72600033610ba7565b610b8e5760405162461bcd60e51b81526004016103a090611476565b610b99600082610efb565b610ba4600033610e8c565b50565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b610bdb600033610ba7565b610bf75760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e83398151915282610efb565b610c1a600033610ba7565b610c365760405162461bcd60e51b81526004016103a090611476565b60005b815181101561052157610c7360008051602061166e833981519152838381518110610c6657610c666113f3565b6020026020010151610efb565b7f28b26e7a3d20aedbc5f8f2ebf7da671c0491723a2b78f47a097b0e46dee07142828281518110610ca657610ca66113f3565b6020026020010151604051610cca91906001600160a01b0391909116815260200190565b60405180910390a180610cdc8161141f565b915050610c39565b600082815260208190526040902060010154610cff81610ef1565b61054a8383610e8c565b6000610d2360008051602061166e83398151915233610ba7565b610d3f5760405162461bcd60e51b81526004016103a0906114be565b60008330604051602001610d54929190611509565b60405160208183030381529060405280519060200120905060008330604051602001610d81929190611509565b60408051601f1981840301815291815281516020928301206000858152600290935291206001015490915060ff1680610dcb575060008181526002602052604090206001015460ff165b95945050505050565b6000610dee60008051602061166e83398151915233610ba7565b610e0a5760405162461bcd60e51b81526004016103a0906114be565b60008230604051602001610e1f929190611509565b60408051808303601f1901815291815281516020928301206000908152600290925290206001015460ff169392505050565b610e5c600033610ba7565b610e785760405162461bcd60e51b81526004016103a090611476565b610ba460008051602061168e833981519152825b610e968282610ba7565b15610521576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610ba48133610f7f565b610f058282610ba7565b610521576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055610f3b3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b610f898282610ba7565b61052157610f9681610fd8565b610fa1836020610fea565b604051602001610fb2929190611577565b60408051601f198184030181529082905262461bcd60e51b82526103a0916004016115ec565b60606103666001600160a01b03831660145b60606000610ff983600261161f565b61100490600261163e565b67ffffffffffffffff81111561101c5761101c61122c565b6040519080825280601f01601f191660200182016040528015611046576020820181803683370190505b509050600360fc1b81600081518110611061576110616113f3565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611090576110906113f3565b60200101906001600160f81b031916908160001a90535060006110b484600261161f565b6110bf90600161163e565b90505b6001811115611137576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106110f3576110f36113f3565b1a60f81b828281518110611109576111096113f3565b60200101906001600160f81b031916908160001a90535060049490941c9361113081611656565b90506110c2565b5083156111865760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016103a0565b9392505050565b60006020828403121561119f57600080fd5b81356001600160e01b03198116811461118657600080fd5b600080602083850312156111ca57600080fd5b823567ffffffffffffffff808211156111e257600080fd5b818501915085601f8301126111f657600080fd5b81358181111561120557600080fd5b8660208260051b850101111561121a57600080fd5b60209290920196919550909350505050565b634e487b7160e01b600052604160045260246000fd5b80356001600160a01b0381168114610b6257600080fd5b6000602080838503121561126c57600080fd5b823567ffffffffffffffff8082111561128457600080fd5b818501915085601f83011261129857600080fd5b8135818111156112aa576112aa61122c565b8060051b604051601f19603f830116810181811085821117156112cf576112cf61122c565b6040529182528482019250838101850191888311156112ed57600080fd5b938501935b828510156113125761130385611242565b845293850193928501926112f2565b98975050505050505050565b60006020828403121561133057600080fd5b5035919050565b6000806040838503121561134a57600080fd5b8235915061135a60208401611242565b90509250929050565b60006020828403121561137557600080fd5b61118682611242565b6000806040838503121561139157600080fd5b61139a83611242565b915061135a60208401611242565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a206f706572617460408201526a1bdc881c995c5d5a5c995960aa1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060001982141561143357611433611409565b5060010190565b6020808252810182905260006001600160fb1b0383111561145a57600080fd5b8260051b80856040850137600092016040019182525092915050565b60208082526028908201527f48797065726e6174697665204f7261636c65206572726f723a2061646d696e206040820152671c995c5d5a5c995960c21b606082015260800190565b6020808252602b908201527f48797065726e6174697665204f7261636c65206572726f723a20636f6e73756d60408201526a195c881c995c5d5a5c995960aa1b606082015260800190565b6bffffffffffffffffffffffff19606093841b811682529190921b16601482015260280190565b60008282101561154257611542611409565b500390565b60005b8381101561156257818101518382015260200161154a565b83811115611571576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516115af816017850160208801611547565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516115e0816028840160208801611547565b01602801949350505050565b602081526000825180602084015261160b816040850160208701611547565b601f01601f19169190910160400192915050565b600081600019048311821515161561163957611639611409565b500290565b6000821982111561165157611651611409565b500190565b60008161166557611665611409565b50600019019056fe9d56108290ea0bc9c5c59c3ad357dca9d1b29ed7f3ae1443bef2fa2159bdf5e897667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929a26469706673582212202209b92945b24aecf31433a99250e9597a1896fe78c53ca40e585638df2ca28c64736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "changeTimeThreshold(uint256)": { + "details": "Admin only function, can be used to block any interaction with the protocol, meassured in seconds" + }, + "getRoleAdmin(bytes32)": { + "details": "Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}." + }, + "grantRole(bytes32,address)": { + "details": "Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event." + }, + "hasRole(bytes32,address)": { + "details": "Returns `true` if `account` has been granted `role`." + }, + "renounceRole(bytes32,address)": { + "details": "Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event." + }, + "revokeRole(bytes32,address)": { + "details": "Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event." + }, + "supportsInterface(bytes4)": { + "details": "See {IERC165-supportsInterface}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 6133, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "_roles", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(RoleData)6128_storage)" + }, + { + "astId": 69724, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "threshold", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 69729, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "accountHashToRecord", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_bytes32,t_struct(OracleRecord)69711_storage)" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => bool)", + "numberOfBytes": "32", + "value": "t_bool" + }, + "t_mapping(t_bytes32,t_struct(OracleRecord)69711_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct HypernativeOracle.OracleRecord)", + "numberOfBytes": "32", + "value": "t_struct(OracleRecord)69711_storage" + }, + "t_mapping(t_bytes32,t_struct(RoleData)6128_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct AccessControl.RoleData)", + "numberOfBytes": "32", + "value": "t_struct(RoleData)6128_storage" + }, + "t_struct(OracleRecord)69711_storage": { + "encoding": "inplace", + "label": "struct HypernativeOracle.OracleRecord", + "members": [ + { + "astId": 69708, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "registrationTime", + "offset": 0, + "slot": "0", + "type": "t_uint256" + }, + { + "astId": 69710, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "isPotentialRisk", + "offset": 0, + "slot": "1", + "type": "t_bool" + } + ], + "numberOfBytes": "64" + }, + "t_struct(RoleData)6128_storage": { + "encoding": "inplace", + "label": "struct AccessControl.RoleData", + "members": [ + { + "astId": 6125, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "members", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_bool)" + }, + { + "astId": 6127, + "contract": "contracts/oracleprotection/HypernativeOracle.sol:HypernativeOracle", + "label": "adminRole", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderCommitmentForwarderAlpha.json b/packages/contracts/deployments/apechain/LenderCommitmentForwarderAlpha.json new file mode 100644 index 000000000..19f7e6847 --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderCommitmentForwarderAlpha.json @@ -0,0 +1,1189 @@ +{ + "address": "0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515", + "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": "getUniswapPriceRatioForPool", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_poolRouteConfig", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "priceRatio" + } + ] + }, + { + "type": "function", + "name": "getUniswapPriceRatioForPoolRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "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" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "priceRatio" + } + ] + }, + { + "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": "0x0c414be1fa3b892c087cb87b9c6b133ae39bfd43841de723f693253945f605c5", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x7601a53e0e6d24f89464080179bf0c267508736c1a96a8fb83ef0832a44d61c4", + "blockNumber": 33944592 + }, + "numDeployments": 1, + "implementation": "0xCAed03f8c7410F327F7E535bd7a339ee4b14Ab9b" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV2.json b/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV2.json new file mode 100644 index 000000000..05b5cce7e --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV2.json @@ -0,0 +1,2017 @@ +{ + "address": "0x645b73AF74D14B488EC296a5C0D00270DDd17Cd6", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + }, + { + "type": "address", + "name": "_uniswapV3Factory" + }, + { + "type": "address", + "name": "_uniswapPricingHelper" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "STANDARD_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_PRICING_HELPER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_V3_FACTORY", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalForCollateralForPoolRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple[]", + "name": "poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "poolIsActivated", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "poolOracleRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMaxPrincipalPerCollateralAmount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_maxPrincipalPerCollateralAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayBypassForAccount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_addr" + }, + { + "type": "bool", + "name": "_bypass" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayBypassForAccount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0xf6E926D7282Ba2Dc1bd580dA36420d2067bEc4A3" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V2.json b/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V2.json new file mode 100644 index 000000000..ba81d64ec --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V2.json @@ -0,0 +1,218 @@ +{ + "address": "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "tuple[]", + "name": "_poolOracleRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x352879e528664e781286b1b9982223ac3f25038cd151cdd1a672fafd309d7730", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0xe768124f6ca4093a2edf365e6c7b9bbb24feb7baf52c10497882660dc25f7bb7", + "blockNumber": 33944626 + }, + "numDeployments": 1, + "implementation": "0x437b82f48Cd7E60742C87f4DF45eCf13B6CA935c" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderManager.json b/packages/contracts/deployments/apechain/LenderManager.json new file mode 100644 index 000000000..8f324bb48 --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderManager.json @@ -0,0 +1,441 @@ +{ + "address": "0x0AeeeD450EcCaFaA140222De43963B179B514540", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_marketRegistry" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "approved", + "indexed": true + }, + { + "type": "uint256", + "name": "tokenId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ApprovalForAll", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "operator", + "indexed": true + }, + { + "type": "bool", + "name": "approved", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "tokenId", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getApproved", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isApprovedForAll", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "operator" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "marketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ownerOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "registerLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_newLender" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "safeTransferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "safeTransferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + }, + { + "type": "bytes", + "name": "data" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setApprovalForAll", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "operator" + }, + { + "type": "bool", + "name": "approved" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "supportsInterface", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "bytes4", + "name": "interfaceId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "tokenURI", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "tokenId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0xa33a5626479d237b8c7b1279cbbf6762ee4263585303c9015f69dbb7d32d5e88", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0xbb9855039da72d1c55aea7bcfb035277d5b401a1fd090a2bd240bd8a7133f64f", + "blockNumber": 33944610 + }, + "numDeployments": 1, + "implementation": "0xb7695470E9c8d6E84F4786C240960B7822106b63" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/MarketLiquidityRewards.json b/packages/contracts/deployments/apechain/MarketLiquidityRewards.json new file mode 100644 index 000000000..3fefaa48a --- /dev/null +++ b/packages/contracts/deployments/apechain/MarketLiquidityRewards.json @@ -0,0 +1,405 @@ +{ + "address": "0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_marketRegistry" + }, + { + "type": "address", + "name": "_collateralManager" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ClaimedRewards", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + }, + { + "type": "address", + "name": "recipient", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CreatedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "address", + "name": "allocator", + "indexed": false + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DecreasedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DeletedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "IncreasedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + }, + { + "type": "uint256", + "name": "amount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UpdatedAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocationId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "allocateRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_allocation", + "components": [ + { + "type": "address", + "name": "allocator" + }, + { + "type": "address", + "name": "rewardTokenAddress" + }, + { + "type": "uint256", + "name": "rewardTokenAmount" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "requiredPrincipalTokenAddress" + }, + { + "type": "address", + "name": "requiredCollateralTokenAddress" + }, + { + "type": "uint256", + "name": "minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "bidStartTimeMin" + }, + { + "type": "uint32", + "name": "bidStartTimeMax" + }, + { + "type": "uint8", + "name": "allocationStrategy" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "allocationId_" + } + ] + }, + { + "type": "function", + "name": "allocatedRewards", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "allocator" + }, + { + "type": "address", + "name": "rewardTokenAddress" + }, + { + "type": "uint256", + "name": "rewardTokenAmount" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "requiredPrincipalTokenAddress" + }, + { + "type": "address", + "name": "requiredCollateralTokenAddress" + }, + { + "type": "uint256", + "name": "minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "bidStartTimeMin" + }, + { + "type": "uint32", + "name": "bidStartTimeMax" + }, + { + "type": "uint8", + "name": "allocationStrategy" + } + ] + }, + { + "type": "function", + "name": "claimRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "deallocateRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_tokenAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getRewardTokenAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllocationAmount", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_tokenAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "rewardClaimedForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + }, + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "updateAllocation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_allocationId" + }, + { + "type": "uint256", + "name": "_minimumCollateralPerPrincipalAmount" + }, + { + "type": "uint256", + "name": "_rewardPerLoanPrincipalAmount" + }, + { + "type": "uint32", + "name": "_bidStartTimeMin" + }, + { + "type": "uint32", + "name": "_bidStartTimeMax" + } + ], + "outputs": [] + } + ], + "transactionHash": "0xdfdd739a69e9844c0c8a1e751478e43df55a5cf6003f17c973c994c1e6d87666", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x0a2b9f9275d8a86f4ccb25483f7a2113bbddd0d3a760999b95bfb51252cebdec", + "blockNumber": 33944631 + }, + "numDeployments": 1, + "implementation": "0x5360af9B95701504F783d8654bA02B0AF5155f64" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/MarketRegistry.json b/packages/contracts/deployments/apechain/MarketRegistry.json new file mode 100644 index 000000000..d976611da --- /dev/null +++ b/packages/contracts/deployments/apechain/MarketRegistry.json @@ -0,0 +1,1390 @@ +{ + "address": "0x0708480670BdE591e275B06Cd19EcaDFC93A1f16", + "abi": [ + { + "type": "error", + "name": "NotPayable", + "inputs": [] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerExitMarket", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerRevocation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "borrower", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderExitMarket", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LenderRevocation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketClosed", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketCreated", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetBidExpirationTime", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketBorrowerAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "bool", + "name": "required", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketFee", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint16", + "name": "feePct", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketFeeRecipient", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "newRecipient", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketLenderAttestation", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "bool", + "name": "required", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketOwner", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "newOwner", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketPaymentType", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint8", + "name": "paymentType", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetMarketURI", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "string", + "name": "uri", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentCycle", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint8", + "name": "paymentCycleType", + "indexed": false + }, + { + "type": "uint32", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentCycleDuration", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SetPaymentDefaultDuration", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "duration", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CURRENT_CODE_VERSION", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_MARKET_FEE_PERCENT", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "attestBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + }, + { + "type": "uint8", + "name": "_v" + }, + { + "type": "bytes32", + "name": "_r" + }, + { + "type": "bytes32", + "name": "_s" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + }, + { + "type": "uint8", + "name": "_v" + }, + { + "type": "bytes32", + "name": "_r" + }, + { + "type": "bytes32", + "name": "_s" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "attestLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + }, + { + "type": "uint256", + "name": "_expirationTime" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "borrowerAttestationSchemaId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowerExitMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "closeMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "createMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_initialOwner" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_requireLenderAttestation" + }, + { + "type": "bool", + "name": "_requireBorrowerAttestation" + }, + { + "type": "uint8", + "name": "_paymentType" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "marketId_" + } + ] + }, + { + "type": "function", + "name": "createMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_initialOwner" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_requireLenderAttestation" + }, + { + "type": "bool", + "name": "_requireBorrowerAttestation" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "marketId_" + } + ] + }, + { + "type": "function", + "name": "getAllVerifiedBorrowersForMarket", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint256", + "name": "_page" + }, + { + "type": "uint256", + "name": "_perPage" + } + ], + "outputs": [ + { + "type": "address[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getAllVerifiedLendersForMarket", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint256", + "name": "_page" + }, + { + "type": "uint256", + "name": "_perPage" + } + ], + "outputs": [ + { + "type": "address[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBidExpirationTime", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketAttestationRequirements", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "lenderAttestationRequired" + }, + { + "type": "bool", + "name": "borrowerAttestationRequired" + } + ] + }, + { + "type": "function", + "name": "getMarketData", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "uint32", + "name": "paymentCycleDuration" + }, + { + "type": "uint32", + "name": "paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "loanExpirationTime" + }, + { + "type": "string", + "name": "metadataURI" + }, + { + "type": "uint16", + "name": "marketplaceFeePercent" + }, + { + "type": "bool", + "name": "lenderAttestationRequired" + } + ] + }, + { + "type": "function", + "name": "getMarketFeeRecipient", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketOwner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketURI", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketplaceFee", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "fee" + } + ] + }, + { + "type": "function", + "name": "getPaymentCycle", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + }, + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPaymentDefaultDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPaymentType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerAS" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isMarketClosed", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isMarketOpen", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isPayable", + "constant": true, + "stateMutability": "pure", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isVerifiedBorrower", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + } + ], + "outputs": [ + { + "type": "bool", + "name": "isVerified_" + }, + { + "type": "bytes32", + "name": "uuid_" + } + ] + }, + { + "type": "function", + "name": "isVerifiedLender", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + } + ], + "outputs": [ + { + "type": "bool", + "name": "isVerified_" + }, + { + "type": "bytes32", + "name": "uuid_" + } + ] + }, + { + "type": "function", + "name": "lenderAttestationSchemaId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderExitMarket", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketCount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "resolve", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "address", + "name": "recipient" + }, + { + "type": "bytes", + "name": "schema" + }, + { + "type": "bytes", + "name": "data" + }, + { + "type": "uint256", + "name": "" + }, + { + "type": "address", + "name": "attestor" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "revokeBorrower", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_borrowerAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "revokeLender", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_lenderAddress" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setBidExpirationTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setBorrowerAttestationRequired", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "bool", + "name": "_required" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setLenderAttestationRequired", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "bool", + "name": "_required" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketFeePercent", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint16", + "name": "_newPercent" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketFeeRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketPaymentType", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint8", + "name": "_newPaymentType" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setMarketURI", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "string", + "name": "_uri" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setPaymentCycle", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setPaymentDefaultDuration", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_duration" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerAS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferMarketOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "updateMarketSettings", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "uint32", + "name": "_paymentCycleDuration" + }, + { + "type": "uint8", + "name": "_newPaymentType" + }, + { + "type": "uint8", + "name": "_paymentCycleType" + }, + { + "type": "uint32", + "name": "_paymentDefaultDuration" + }, + { + "type": "uint32", + "name": "_bidExpirationTime" + }, + { + "type": "uint16", + "name": "_feePercent" + }, + { + "type": "bool", + "name": "_borrowerAttestationRequired" + }, + { + "type": "bool", + "name": "_lenderAttestationRequired" + }, + { + "type": "string", + "name": "_metadataURI" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "version", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "receive", + "stateMutability": "payable" + } + ], + "transactionHash": "0x424efe84c9340a420d1df1b7b41b132fbe2f3b97b945b2ccdeddd3eef1e5c2ad", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x9faf17549f5dc9603005ea191ebafc402665259f817efdf20397a86d74062bf9", + "blockNumber": 33944590 + }, + "numDeployments": 1, + "implementation": "0x0D1047229B9851eACE463Fb25f27982a5127c20F" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/MetaForwarder.json b/packages/contracts/deployments/apechain/MetaForwarder.json new file mode 100644 index 000000000..9a543158b --- /dev/null +++ b/packages/contracts/deployments/apechain/MetaForwarder.json @@ -0,0 +1,155 @@ +{ + "address": "0xe7768f28455eE81D7B415f4F5019A316c27AB445", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "execute", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "tuple", + "name": "req", + "components": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "uint256", + "name": "gas" + }, + { + "type": "uint256", + "name": "nonce" + }, + { + "type": "bytes", + "name": "data" + } + ] + }, + { + "type": "bytes", + "name": "signature" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + }, + { + "type": "bytes", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getNonce", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "verify", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "req", + "components": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "value" + }, + { + "type": "uint256", + "name": "gas" + }, + { + "type": "uint256", + "name": "nonce" + }, + { + "type": "bytes", + "name": "data" + } + ] + }, + { + "type": "bytes", + "name": "signature" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + } + ], + "transactionHash": "0xd6652a090a359c4dee65f71bc7ecb37f0b5366ab57c4d77d992e12685503aa03", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x4f46d85c96d1953c0221da4360dfd05fd5a781fbe5c61b8921e36b3e6083c1a4", + "blockNumber": 33944569 + }, + "numDeployments": 1, + "implementation": "0x0258eAE8bBEf65c523A78705Fe80a82fD75e258d" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/ProtocolPausingManager.json b/packages/contracts/deployments/apechain/ProtocolPausingManager.json new file mode 100644 index 000000000..f16fee473 --- /dev/null +++ b/packages/contracts/deployments/apechain/ProtocolPausingManager.json @@ -0,0 +1,310 @@ +{ + "address": "0x357fa5700f67a3DA1EC49ea19F872B3a35fE043D", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidations", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedProtocol", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PauserAdded", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PauserRemoved", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidations", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedProtocol", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "addPauser", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_pauser" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getLastPausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isPauser", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidationsPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseLiquidations", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseProtocol", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauserRoleBearer", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "protocolPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "removePauser", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_pauser" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidations", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseProtocol", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + } + ], + "transactionHash": "0x7f305ae2a6142aa8d4bfe6625bd846dc08b503df62bcb1acfb21313f1bdc2623", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0xbb8e32ac421474caef34c171da6440683da0a991f00ff39df58927668c7fe40e", + "blockNumber": 33944616 + }, + "numDeployments": 1, + "implementation": "0x13a5735F356B4ede9D3F65D3eDdb62651df1cC37" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/ReputationManager.json b/packages/contracts/deployments/apechain/ReputationManager.json new file mode 100644 index 000000000..c6c38e2da --- /dev/null +++ b/packages/contracts/deployments/apechain/ReputationManager.json @@ -0,0 +1,218 @@ +{ + "address": "0x48EE9c344d5C6d202F4b3225A694957a3412008d", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarkAdded", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + }, + { + "type": "uint8", + "name": "repMark", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarkRemoved", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": true + }, + { + "type": "uint8", + "name": "repMark", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CONTROLLER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCurrentDefaultLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCurrentDelinquentLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getDefaultedLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getDelinquentLoanIds", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "tellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "updateAccountReputation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "updateAccountReputation", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + }, + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + } + ], + "transactionHash": "0x84b1a9916fc64dd4a489ab58cb3aa39c6afb0293e9cb9ba05b04e15bf12a6961", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x59ef33b6d2c55d231d1a1011cfa356b64116a5508e6832d3f8a566d96b23b5e3", + "blockNumber": 33944607 + }, + "numDeployments": 1, + "implementation": "0x7292385522F11390B2A7dd4677528fFce03b80db" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/SmartCommitmentForwarder.json b/packages/contracts/deployments/apechain/SmartCommitmentForwarder.json new file mode 100644 index 000000000..63cd3ef7d --- /dev/null +++ b/packages/contracts/deployments/apechain/SmartCommitmentForwarder.json @@ -0,0 +1,578 @@ +{ + "address": "0x7f43c21D4FE1807BF2CF25e6F048A03b57226e03", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_protocolAddress" + }, + { + "type": "address", + "name": "_marketRegistry" + } + ] + }, + { + "type": "error", + "name": "InsufficientBorrowerCollateral", + "inputs": [ + { + "type": "uint256", + "name": "required" + }, + { + "type": "uint256", + "name": "actual" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ExercisedSmartCommitment", + "inputs": [ + { + "type": "address", + "name": "smartCommitmentAddress", + "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": "OracleAddressChanged", + "inputs": [ + { + "type": "address", + "name": "previousOracle", + "indexed": true + }, + { + "type": "address", + "name": "newOracle", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "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": "acceptSmartCommitmentWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_smartCommitmentAddress" + }, + { + "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": "addExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLiquidationProtocolFeePercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "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": "hasExtension", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + }, + { + "type": "address", + "name": "extension" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "hypernativeOracleIsStrictMode", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "isOracleApproved", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isOracleApprovedAllowEOA", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isOracleApprovedOnlyAllowEOA", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_sender" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidationProtocolFeePercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "oracleRegister", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_account" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pause", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "revokeExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setIsStrictMode", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "bool", + "name": "_mode" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setLiquidationProtocolFeePercent", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_percent" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setOracle", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_oracle" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpause", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + } + ], + "transactionHash": "0x2e602e44bf768ea756b819e26572332e4b381a7127e95b6df20c22383ad45db7", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x54248d0df56d5eb2652df97ff670a597d8df82a5209801a22dc848b98e4609f2", + "blockNumber": 33944599 + }, + "numDeployments": 1, + "implementation": "0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/SwapRolloverLoan.json b/packages/contracts/deployments/apechain/SwapRolloverLoan.json new file mode 100644 index 000000000..e8380a10d --- /dev/null +++ b/packages/contracts/deployments/apechain/SwapRolloverLoan.json @@ -0,0 +1,514 @@ +{ + "address": "0x7FBCefE4aE4c0C9E70427D0B9F1504Ed39d141BC", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_factory" + }, + { + "type": "address", + "name": "_WETH9" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "RolloverLoanComplete", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": false + }, + { + "type": "uint256", + "name": "originalLoanId", + "indexed": false + }, + { + "type": "uint256", + "name": "newLoanId", + "indexed": false + }, + { + "type": "uint256", + "name": "fundsRemaining", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "RolloverWithReferral", + "inputs": [ + { + "type": "uint256", + "name": "newLoanId", + "indexed": false + }, + { + "type": "address", + "name": "flashToken", + "indexed": false + }, + { + "type": "address", + "name": "rewardRecipient", + "indexed": false + }, + { + "type": "uint256", + "name": "rewardAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "atmId", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "WETH9", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateRolloverAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "marketFeePct" + }, + { + "type": "uint16", + "name": "protocolFeePct" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "_rewardAmount" + }, + { + "type": "uint16", + "name": "_flashloanFeePct" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "_flashAmount" + }, + { + "type": "int256", + "name": "_borrowerAmount" + } + ] + }, + { + "type": "function", + "name": "factory", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketFeePct", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketIdForCommitment", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getUniswapPoolAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "refundETH", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "rolloverLoanWithFlashSwap", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "_borrowerAmount" + }, + { + "type": "tuple", + "name": "_flashSwapArgs", + "components": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + }, + { + "type": "uint256", + "name": "flashAmount" + }, + { + "type": "bool", + "name": "borrowToken1" + } + ] + }, + { + "type": "tuple", + "name": "_acceptCommitmentArgs", + "components": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "address", + "name": "smartCommitmentAddress" + }, + { + "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": "function", + "name": "rolloverLoanWithFlashSwapRewards", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "uint256", + "name": "_loanId" + }, + { + "type": "uint256", + "name": "_borrowerAmount" + }, + { + "type": "uint256", + "name": "_rewardAmount" + }, + { + "type": "address", + "name": "_rewardRecipient" + }, + { + "type": "uint256", + "name": "_atmId" + }, + { + "type": "tuple", + "name": "_flashSwapArgs", + "components": [ + { + "type": "address", + "name": "token0" + }, + { + "type": "address", + "name": "token1" + }, + { + "type": "uint24", + "name": "fee" + }, + { + "type": "uint256", + "name": "flashAmount" + }, + { + "type": "bool", + "name": "borrowToken1" + } + ] + }, + { + "type": "tuple", + "name": "_acceptCommitmentArgs", + "components": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "address", + "name": "smartCommitmentAddress" + }, + { + "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": "function", + "name": "sweepToken", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "address", + "name": "token" + }, + { + "type": "uint256", + "name": "amountMinimum" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "uniswapV3FlashCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "fee0" + }, + { + "type": "uint256", + "name": "fee1" + }, + { + "type": "bytes", + "name": "data" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unwrapWETH9", + "constant": false, + "stateMutability": "payable", + "payable": true, + "inputs": [ + { + "type": "uint256", + "name": "amountMinimum" + }, + { + "type": "address", + "name": "recipient" + } + ], + "outputs": [] + }, + { + "type": "receive", + "stateMutability": "payable" + } + ], + "transactionHash": "0xff412445c8d7692f8472f2546fbf59387bfb331ccd5aa74bfcbeee47ae5ec080", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x9709ef2ae36dc72125076300574b78133a78e0290d15cdbf6a3b5b4f6d02cb2e", + "blockNumber": 33944597 + }, + "numDeployments": 1, + "implementation": "0xfCd6Aa92D399260E8309800316CEc9b1F123621e" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/TellerAS.json b/packages/contracts/deployments/apechain/TellerAS.json new file mode 100644 index 000000000..5a7dfcf90 --- /dev/null +++ b/packages/contracts/deployments/apechain/TellerAS.json @@ -0,0 +1,1089 @@ +{ + "address": "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", + "abi": [ + { + "inputs": [ + { + "internalType": "contract IASRegistry", + "name": "registry", + "type": "address" + }, + { + "internalType": "contract IEASEIP712Verifier", + "name": "verifier", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "AccessDenied", + "type": "error" + }, + { + "inputs": [], + "name": "AlreadyRevoked", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidAttestation", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidExpirationTime", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidOffset", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidRegistry", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidSchema", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidVerifier", + "type": "error" + }, + { + "inputs": [], + "name": "NotFound", + "type": "error" + }, + { + "inputs": [], + "name": "NotPayable", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "Attested", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "Revoked", + "type": "event" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "attest", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "attestByDelegation", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [], + "name": "getASRegistry", + "outputs": [ + { + "internalType": "contract IASRegistry", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getAttestation", + "outputs": [ + { + "components": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint256", + "name": "time", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "revocationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "internalType": "struct IEAS.Attestation", + "name": "", + "type": "tuple" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getAttestationsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getEIP712Verifier", + "outputs": [ + { + "internalType": "contract IEASEIP712Verifier", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getLastUUID", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getReceivedAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getReceivedAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getRelatedAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getRelatedAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getSchemaAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getSchemaAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "start", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "length", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "reverseOrder", + "type": "bool" + } + ], + "name": "getSentAttestationUUIDs", + "outputs": [ + { + "internalType": "bytes32[]", + "name": "", + "type": "bytes32[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + } + ], + "name": "getSentAttestationUUIDsCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "isAttestationActive", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "isAttestationValid", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "revoke", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "revokeByDelegation", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xbd66f9db8b3ae1ba1c8c47c0cdb21565aece62d88fe350d19d2d1cb3941a9a97", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x47ed489BBE38a198254Ecbac79ECd68860455BBf", + "transactionIndex": 1, + "gasUsed": "1476512", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xf219fca17ede20a6cca8ff81633457fbc66a8d9b419b603da9a28344e41a5f70", + "transactionHash": "0xbd66f9db8b3ae1ba1c8c47c0cdb21565aece62d88fe350d19d2d1cb3941a9a97", + "logs": [], + "blockNumber": 33944585, + "cumulativeGasUsed": "1476512", + "status": 1, + "byzantium": true + }, + "args": [ + "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", + "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"contract IASRegistry\",\"name\":\"registry\",\"type\":\"address\"},{\"internalType\":\"contract IEASEIP712Verifier\",\"name\":\"verifier\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"AccessDenied\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"AlreadyRevoked\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidAttestation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidExpirationTime\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidOffset\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidRegistry\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSchema\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidVerifier\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotFound\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"NotPayable\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"Attested\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"Revoked\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"attest\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"attestByDelegation\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getASRegistry\",\"outputs\":[{\"internalType\":\"contract IASRegistry\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getAttestation\",\"outputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"time\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"revocationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"internalType\":\"struct IEAS.Attestation\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getAttestationsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getEIP712Verifier\",\"outputs\":[{\"internalType\":\"contract IEASEIP712Verifier\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getLastUUID\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getReceivedAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getReceivedAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getRelatedAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getRelatedAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getSchemaAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getSchemaAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"reverseOrder\",\"type\":\"bool\"}],\"name\":\"getSentAttestationUUIDs\",\"outputs\":[{\"internalType\":\"bytes32[]\",\"name\":\"\",\"type\":\"bytes32[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"}],\"name\":\"getSentAttestationUUIDsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"isAttestationActive\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"isAttestationValid\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"revoke\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"revokeByDelegation\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"attest(address,bytes32,uint256,bytes32,bytes)\":{\"details\":\"Attests to a specific AS.\",\"params\":{\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The UUID of the new attestation.\"}},\"attestByDelegation(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)\":{\"details\":\"Attests to a specific AS using a provided EIP712 signature.\",\"params\":{\"attester\":\"The attesting account.\",\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"r\":\"The x-coordinate of the nonce R.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"s\":\"The signature data.\",\"schema\":\"The UUID of the AS.\",\"v\":\"The recovery ID.\"},\"returns\":{\"_0\":\"The UUID of the new attestation.\"}},\"constructor\":{\"details\":\"Creates a new EAS instance.\",\"params\":{\"registry\":\"The address of the global AS registry.\",\"verifier\":\"The address of the EIP712 verifier.\"}},\"getASRegistry()\":{\"details\":\"Returns the address of the AS global registry.\",\"returns\":{\"_0\":\"The address of the AS global registry.\"}},\"getAttestation(bytes32)\":{\"details\":\"Returns an existing attestation by UUID.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"The attestation data members.\"}},\"getAttestationsCount()\":{\"details\":\"Returns the global counter for the total number of attestations.\",\"returns\":{\"_0\":\"The global counter for the total number of attestations.\"}},\"getEIP712Verifier()\":{\"details\":\"Returns the address of the EIP712 verifier used to verify signed attestations.\",\"returns\":{\"_0\":\"The address of the EIP712 verifier used to verify signed attestations.\"}},\"getReceivedAttestationUUIDs(address,bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all received attestation UUIDs.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"recipient\":\"The recipient of the attestation.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getReceivedAttestationUUIDsCount(address,bytes32)\":{\"details\":\"Returns the number of received attestation UUIDs.\",\"params\":{\"recipient\":\"The recipient of the attestation.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"getRelatedAttestationUUIDs(bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all attestations related to a specific attestation.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"start\":\"The offset to start from.\",\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getRelatedAttestationUUIDsCount(bytes32)\":{\"details\":\"Returns the number of related attestation UUIDs.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"The number of related attestations.\"}},\"getSchemaAttestationUUIDs(bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all per-schema attestation UUIDs.\",\"params\":{\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getSchemaAttestationUUIDsCount(bytes32)\":{\"details\":\"Returns the number of per-schema attestation UUIDs.\",\"params\":{\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"getSentAttestationUUIDs(address,bytes32,uint256,uint256,bool)\":{\"details\":\"Returns all sent attestation UUIDs.\",\"params\":{\"attester\":\"The attesting account.\",\"length\":\"The number of total members to retrieve.\",\"reverseOrder\":\"Whether the offset starts from the end and the data is returned in reverse.\",\"schema\":\"The UUID of the AS.\",\"start\":\"The offset to start from.\"},\"returns\":{\"_0\":\"An array of attestation UUIDs.\"}},\"getSentAttestationUUIDsCount(address,bytes32)\":{\"details\":\"Returns the number of sent attestation UUIDs.\",\"params\":{\"recipient\":\"The recipient of the attestation.\",\"schema\":\"The UUID of the AS.\"},\"returns\":{\"_0\":\"The number of attestations.\"}},\"isAttestationActive(bytes32)\":{\"details\":\"Checks whether an attestation is active.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"Whether an attestation is active.\"}},\"isAttestationValid(bytes32)\":{\"details\":\"Checks whether an attestation exists.\",\"params\":{\"uuid\":\"The UUID of the attestation to retrieve.\"},\"returns\":{\"_0\":\"Whether an attestation exists.\"}},\"revoke(bytes32)\":{\"details\":\"Revokes an existing attestation to a specific AS.\",\"params\":{\"uuid\":\"The UUID of the attestation to revoke.\"}},\"revokeByDelegation(bytes32,address,uint8,bytes32,bytes32)\":{\"details\":\"Attests to a specific AS using a provided EIP712 signature.\",\"params\":{\"attester\":\"The attesting account.\",\"r\":\"The x-coordinate of the nonce R.\",\"s\":\"The signature data.\",\"uuid\":\"The UUID of the attestation to revoke.\",\"v\":\"The recovery ID.\"}}},\"title\":\"TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerAS.sol\":\"TellerAS\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60c06040523480156200001157600080fd5b5060405162001ade38038062001ade8339810160408190526200003491620000b5565b6001600160a01b0382166200005c576040516311a1e69760e01b815260040160405180910390fd5b6001600160a01b038116620000845760405163baa3de5f60e01b815260040160405180910390fd5b6001600160a01b039182166080521660a052620000f4565b6001600160a01b0381168114620000b257600080fd5b50565b60008060408385031215620000c957600080fd5b8251620000d6816200009c565b6020840151909250620000e9816200009c565b809150509250929050565b60805160a0516119af6200012f600039600081816101b301528181610692015261092501526000818161028701526109cd01526119af6000f3fe60806040526004361061011f5760003560e01c8063a3112a64116100a0578063d8c5ebd411610064578063d8c5ebd4146103a0578063e30bb563146103e3578063ef0a309814610412578063f96e501314610427578063ffa1ad741461043c57600080fd5b8063a3112a64146102be578063b75c7dc6146102eb578063c042d88f1461030d578063c334947c14610350578063d87647b21461038057600080fd5b806362196643116100e7578063621966431461020b57806363583538146102385780637f04f2841461025857806381fa6cd314610278578063930ed013146102ab57600080fd5b80630560f90f1461012457806309a954cd14610164578063105152981461017757806315cd31a1146101a45780631bc9a07a146101eb575b600080fd5b34801561013057600080fd5b5061015161013f3660046111e8565b60009081526020819052604090205490565b6040519081526020015b60405180910390f35b61015161017236600461125f565b610478565b34801561018357600080fd5b506101976101923660046112e0565b610494565b60405161015b9190611336565b3480156101b057600080fd5b507f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161015b565b3480156101f757600080fd5b506101976102063660046112e0565b61051a565b34801561021757600080fd5b506101516102263660046111e8565b60009081526003602052604090205490565b34801561024457600080fd5b5061019761025336600461137a565b610594565b34801561026457600080fd5b5061019761027336600461137a565b61060c565b34801561028457600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006101d3565b6101516102b93660046113d1565b610678565b3480156102ca57600080fd5b506102de6102d93660046111e8565b610729565b60405161015b91906114d7565b3480156102f757600080fd5b5061030b6103063660046111e8565b61088c565b005b34801561031957600080fd5b50610151610328366004611567565b6001600160a01b03919091166000908152600260209081526040808320938352929052205490565b34801561035c57600080fd5b5061037061036b3660046111e8565b610899565b604051901515815260200161015b565b34801561038c57600080fd5b5061030b61039b366004611593565b6108e8565b3480156103ac57600080fd5b506101516103bb366004611567565b6001600160a01b03919091166000908152600160209081526040808320938352929052205490565b3480156103ef57600080fd5b506103706103fe3660046111e8565b600090815260046020526040902054151590565b34801561041e57600080fd5b50600654610151565b34801561043357600080fd5b50600554610151565b34801561044857600080fd5b5061046b604051806040016040528060038152602001620605c760eb1b81525081565b60405161015b91906115e3565b600061048987878787878733610992565b979650505050505050565b6001600160a01b03851660009081526001602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020905b8154815260200190600101908083116104ef575b5050505050858585610ede565b9695505050505050565b6001600160a01b03851660009081526002602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b60606106016003600087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b90505b949350505050565b606061060160008087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b604051636aeb49a560e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636aeb49a5906106d9908e908e908e908e908e908e908e908e908e908e90600401611626565b600060405180830381600087803b1580156106f357600080fd5b505af1158015610707573d6000803e3d6000fd5b5050505061071a8b8b8b8b8b8b8b610992565b9b9a5050505050505050505050565b604080516101208101825260008082526020820181905291810182905260608082018390526080820183905260a0820183905260c0820183905260e08201929092526101008101919091526000828152600460208181526040928390208351610120810185528154815260018201549281019290925260028101546001600160a01b039081169483019490945260038101549093166060820152908201546080820152600582015460a0820152600682015460c0820152600782015460e08201526008820180549192916101008401919061080390611689565b80601f016020809104026020016040519081016040528092919081815260200182805461082f90611689565b801561087c5780601f106108515761010080835404028352916020019161087c565b820191906000526020600020905b81548152906001019060200180831161085f57829003601f168201915b5050505050815250509050919050565b6108968133611013565b50565b600081815260046020526040812054151580156108c757506000828152600460205260409020600501544211155b80156108e25750600082815260046020526040902060060154155b92915050565b604051631863f01d60e01b8152600481018690526001600160a01b03858116602483015260ff8516604483015260648201849052608482018390527f00000000000000000000000000000000000000000000000000000000000000001690631863f01d9060a401600060405180830381600087803b15801561096957600080fd5b505af115801561097d573d6000803e3d6000fd5b5050505061098b8585611013565b5050505050565b60004286116109b4576040516308e8b93760e01b815260040160405180910390fd5b6040516339243ea960e11b8152600481018890526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906372487d5290602401600060405180830381865afa158015610a1c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610a449190810190611734565b8051909150610a6657604051635f9bd90760e11b815260040160405180910390fd5b60208101516001600160a01b03811615610ba1573415801590610ae85750806001600160a01b031663ce46e0466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ac2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ae6919061181c565b155b15610b0657604051631574f9f360e01b815260040160405180910390fd5b806001600160a01b031663947a75b4348c85606001518a8a8e8b6040518863ffffffff1660e01b8152600401610b4196959493929190611839565b60206040518083038185885af1158015610b5f573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610b84919061181c565b610ba15760405163bd8ba84d60e01b815260040160405180910390fd5b60006040518061012001604052806000801b81526020018b81526020018c6001600160a01b03168152602001866001600160a01b031681526020014281526020018a81526020016000815260200189815260200188888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050509152509050610c38816110e9565b600681905550600654816000018181525050600160008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505560026000866001600160a01b03166001600160a01b0316815260200190815260200160002060008b81526020019081526020016000206006549080600181540180825580915050600190039060005260206000200160009091909190915055600360008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505580600460006006548152602001908152602001600020600082015181600001556020820151816001015560408201518160020160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a0820151816005015560c0820151816006015560e08201518160070155610100820151816008019080519060200190610e0d92919061114f565b50506005805491506000610e20836118a0565b90915550508715610e7c57600088815260046020526040902054610e575760405163c5723b5160e01b815260040160405180910390fd5b6000888152602081815260408220600654815460018101835591845291909220909101555b89856001600160a01b03168c6001600160a01b03167f8bf46bf4cfd674fa735a3d63ec1c9ad4153f033c290341f3a588b75685141b35600654604051610ec491815260200190565b60405180910390a450506006549998505050505050505050565b835160609080610efe575050604080516000815260208101909152610604565b808510610f1d5760405162ed0ab960e11b815260040160405180910390fd5b83610f2881876118bb565b821015610f3c57610f3986836118d3565b90505b60008167ffffffffffffffff811115610f5757610f576116c4565b604051908082528060200260200182016040528015610f80578160200160208202803683370190505b50905060005b82811015611007578886610fa357610f9e828a6118bb565b610fc2565b610fad828a6118bb565b610fb89060016118bb565b610fc290866118d3565b81518110610fd257610fd26118ea565b6020026020010151828281518110610fec57610fec6118ea565b6020908102919091010152611000816118a0565b9050610f86565b50979650505050505050565b600082815260046020526040902080546110405760405163c5723b5160e01b815260040160405180910390fd5b60038101546001600160a01b0383811691161461107057604051634ca8886760e01b815260040160405180910390fd5b6006810154156110935760405163905e710760e01b815260040160405180910390fd5b426006820155600181015460028201546040518581526001600160a01b038581169216907ff930a6e2523c9cc298691873087a740550b8fc85a0680830414c148ed927f6159060200160405180910390a4505050565b6020808201516040808401516060850151608086015160a08701516101008801518551808701875260018152600160fe1b818a0152600554965160009961113299989101611900565b604051602081830303815290604052805190602001209050919050565b82805461115b90611689565b90600052602060002090601f01602090048101928261117d57600085556111c3565b82601f1061119657805160ff19168380011785556111c3565b828001600101855582156111c3579182015b828111156111c35782518255916020019190600101906111a8565b506111cf9291506111d3565b5090565b5b808211156111cf57600081556001016111d4565b6000602082840312156111fa57600080fd5b5035919050565b6001600160a01b038116811461089657600080fd5b60008083601f84011261122857600080fd5b50813567ffffffffffffffff81111561124057600080fd5b60208301915083602082850101111561125857600080fd5b9250929050565b60008060008060008060a0878903121561127857600080fd5b863561128381611201565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff8111156112b457600080fd5b6112c089828a01611216565b979a9699509497509295939492505050565b801515811461089657600080fd5b600080600080600060a086880312156112f857600080fd5b853561130381611201565b94506020860135935060408601359250606086013591506080860135611328816112d2565b809150509295509295909350565b6020808252825182820181905260009190848201906040850190845b8181101561136e57835183529284019291840191600101611352565b50909695505050505050565b6000806000806080858703121561139057600080fd5b84359350602085013592506040850135915060608501356113b0816112d2565b939692955090935050565b803560ff811681146113cc57600080fd5b919050565b6000806000806000806000806000806101208b8d0312156113f157600080fd5b8a356113fc81611201565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff81111561142d57600080fd5b6114398d828e01611216565b90975095505060a08b013561144d81611201565b935061145b60c08c016113bb565b925060e08b013591506101008b013590509295989b9194979a5092959850565b60005b8381101561149657818101518382015260200161147e565b838111156114a5576000848401525b50505050565b600081518084526114c381602086016020860161147b565b601f01601f19169290920160200192915050565b6020815281516020820152602082015160408201526000604083015161150860608401826001600160a01b03169052565b5060608301516001600160a01b038116608084015250608083015160a083015260a083015160c083015260c083015160e083015260e08301516101008181850152808501519150506101208081850152506106046101408401826114ab565b6000806040838503121561157a57600080fd5b823561158581611201565b946020939093013593505050565b600080600080600060a086880312156115ab57600080fd5b8535945060208601356115bd81611201565b93506115cb604087016113bb565b94979396509394606081013594506080013592915050565b6020815260006115f660208301846114ab565b9392505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b600061012060018060a01b03808e1684528c60208501528b60408501528a606085015281608085015261165c8285018a8c6115fd565b971660a0840152505060ff9390931660c084015260e0830191909152610100909101529695505050505050565b600181811c9082168061169d57607f821691505b602082108114156116be57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff811182821017156116fd576116fd6116c4565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561172c5761172c6116c4565b604052919050565b6000602080838503121561174757600080fd5b825167ffffffffffffffff8082111561175f57600080fd5b908401906080828703121561177357600080fd5b61177b6116da565b825181528383015161178c81611201565b81850152604083810151908201526060830151828111156117ac57600080fd5b80840193505086601f8401126117c157600080fd5b8251828111156117d3576117d36116c4565b6117e5601f8201601f19168601611703565b925080835287858286010111156117fb57600080fd5b61180a8186850187870161147b565b50606081019190915295945050505050565b60006020828403121561182e57600080fd5b81516115f6816112d2565b600060018060a01b03808916835260a0602084015261185b60a08401896114ab565b838103604085015261186e81888a6115fd565b6060850196909652509290921660809091015250949350505050565b634e487b7160e01b600052601160045260246000fd5b60006000198214156118b4576118b461188a565b5060010190565b600082198211156118ce576118ce61188a565b500190565b6000828210156118e5576118e561188a565b500390565b634e487b7160e01b600052603260045260246000fd5b88815260006bffffffffffffffffffffffff19808a60601b166020840152808960601b16603484015250866048830152856068830152845161194981608885016020890161147b565b84519083019061196081608884016020890161147b565b016088810193909352505060a80197965050505050505056fea26469706673582212206b83e2d5fb2a34e86903468d36eb72ed8828b1852d24733e2c4f36d7f72717d664736f6c634300080b0033", + "deployedBytecode": "0x60806040526004361061011f5760003560e01c8063a3112a64116100a0578063d8c5ebd411610064578063d8c5ebd4146103a0578063e30bb563146103e3578063ef0a309814610412578063f96e501314610427578063ffa1ad741461043c57600080fd5b8063a3112a64146102be578063b75c7dc6146102eb578063c042d88f1461030d578063c334947c14610350578063d87647b21461038057600080fd5b806362196643116100e7578063621966431461020b57806363583538146102385780637f04f2841461025857806381fa6cd314610278578063930ed013146102ab57600080fd5b80630560f90f1461012457806309a954cd14610164578063105152981461017757806315cd31a1146101a45780631bc9a07a146101eb575b600080fd5b34801561013057600080fd5b5061015161013f3660046111e8565b60009081526020819052604090205490565b6040519081526020015b60405180910390f35b61015161017236600461125f565b610478565b34801561018357600080fd5b506101976101923660046112e0565b610494565b60405161015b9190611336565b3480156101b057600080fd5b507f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161015b565b3480156101f757600080fd5b506101976102063660046112e0565b61051a565b34801561021757600080fd5b506101516102263660046111e8565b60009081526003602052604090205490565b34801561024457600080fd5b5061019761025336600461137a565b610594565b34801561026457600080fd5b5061019761027336600461137a565b61060c565b34801561028457600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006101d3565b6101516102b93660046113d1565b610678565b3480156102ca57600080fd5b506102de6102d93660046111e8565b610729565b60405161015b91906114d7565b3480156102f757600080fd5b5061030b6103063660046111e8565b61088c565b005b34801561031957600080fd5b50610151610328366004611567565b6001600160a01b03919091166000908152600260209081526040808320938352929052205490565b34801561035c57600080fd5b5061037061036b3660046111e8565b610899565b604051901515815260200161015b565b34801561038c57600080fd5b5061030b61039b366004611593565b6108e8565b3480156103ac57600080fd5b506101516103bb366004611567565b6001600160a01b03919091166000908152600160209081526040808320938352929052205490565b3480156103ef57600080fd5b506103706103fe3660046111e8565b600090815260046020526040902054151590565b34801561041e57600080fd5b50600654610151565b34801561043357600080fd5b50600554610151565b34801561044857600080fd5b5061046b604051806040016040528060038152602001620605c760eb1b81525081565b60405161015b91906115e3565b600061048987878787878733610992565b979650505050505050565b6001600160a01b03851660009081526001602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020905b8154815260200190600101908083116104ef575b5050505050858585610ede565b9695505050505050565b6001600160a01b03851660009081526002602090815260408083208784528252918290208054835181840281018401909452808452606093610510939092919083018282801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b60606106016003600087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b90505b949350505050565b606061060160008087815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561050357602002820191906000526020600020908154815260200190600101908083116104ef575050505050858585610ede565b604051636aeb49a560e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636aeb49a5906106d9908e908e908e908e908e908e908e908e908e908e90600401611626565b600060405180830381600087803b1580156106f357600080fd5b505af1158015610707573d6000803e3d6000fd5b5050505061071a8b8b8b8b8b8b8b610992565b9b9a5050505050505050505050565b604080516101208101825260008082526020820181905291810182905260608082018390526080820183905260a0820183905260c0820183905260e08201929092526101008101919091526000828152600460208181526040928390208351610120810185528154815260018201549281019290925260028101546001600160a01b039081169483019490945260038101549093166060820152908201546080820152600582015460a0820152600682015460c0820152600782015460e08201526008820180549192916101008401919061080390611689565b80601f016020809104026020016040519081016040528092919081815260200182805461082f90611689565b801561087c5780601f106108515761010080835404028352916020019161087c565b820191906000526020600020905b81548152906001019060200180831161085f57829003601f168201915b5050505050815250509050919050565b6108968133611013565b50565b600081815260046020526040812054151580156108c757506000828152600460205260409020600501544211155b80156108e25750600082815260046020526040902060060154155b92915050565b604051631863f01d60e01b8152600481018690526001600160a01b03858116602483015260ff8516604483015260648201849052608482018390527f00000000000000000000000000000000000000000000000000000000000000001690631863f01d9060a401600060405180830381600087803b15801561096957600080fd5b505af115801561097d573d6000803e3d6000fd5b5050505061098b8585611013565b5050505050565b60004286116109b4576040516308e8b93760e01b815260040160405180910390fd5b6040516339243ea960e11b8152600481018890526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906372487d5290602401600060405180830381865afa158015610a1c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610a449190810190611734565b8051909150610a6657604051635f9bd90760e11b815260040160405180910390fd5b60208101516001600160a01b03811615610ba1573415801590610ae85750806001600160a01b031663ce46e0466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ac2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ae6919061181c565b155b15610b0657604051631574f9f360e01b815260040160405180910390fd5b806001600160a01b031663947a75b4348c85606001518a8a8e8b6040518863ffffffff1660e01b8152600401610b4196959493929190611839565b60206040518083038185885af1158015610b5f573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610b84919061181c565b610ba15760405163bd8ba84d60e01b815260040160405180910390fd5b60006040518061012001604052806000801b81526020018b81526020018c6001600160a01b03168152602001866001600160a01b031681526020014281526020018a81526020016000815260200189815260200188888080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050509152509050610c38816110e9565b600681905550600654816000018181525050600160008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505560026000866001600160a01b03166001600160a01b0316815260200190815260200160002060008b81526020019081526020016000206006549080600181540180825580915050600190039060005260206000200160009091909190915055600360008b8152602001908152602001600020600654908060018154018082558091505060019003906000526020600020016000909190919091505580600460006006548152602001908152602001600020600082015181600001556020820151816001015560408201518160020160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060608201518160030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816004015560a0820151816005015560c0820151816006015560e08201518160070155610100820151816008019080519060200190610e0d92919061114f565b50506005805491506000610e20836118a0565b90915550508715610e7c57600088815260046020526040902054610e575760405163c5723b5160e01b815260040160405180910390fd5b6000888152602081815260408220600654815460018101835591845291909220909101555b89856001600160a01b03168c6001600160a01b03167f8bf46bf4cfd674fa735a3d63ec1c9ad4153f033c290341f3a588b75685141b35600654604051610ec491815260200190565b60405180910390a450506006549998505050505050505050565b835160609080610efe575050604080516000815260208101909152610604565b808510610f1d5760405162ed0ab960e11b815260040160405180910390fd5b83610f2881876118bb565b821015610f3c57610f3986836118d3565b90505b60008167ffffffffffffffff811115610f5757610f576116c4565b604051908082528060200260200182016040528015610f80578160200160208202803683370190505b50905060005b82811015611007578886610fa357610f9e828a6118bb565b610fc2565b610fad828a6118bb565b610fb89060016118bb565b610fc290866118d3565b81518110610fd257610fd26118ea565b6020026020010151828281518110610fec57610fec6118ea565b6020908102919091010152611000816118a0565b9050610f86565b50979650505050505050565b600082815260046020526040902080546110405760405163c5723b5160e01b815260040160405180910390fd5b60038101546001600160a01b0383811691161461107057604051634ca8886760e01b815260040160405180910390fd5b6006810154156110935760405163905e710760e01b815260040160405180910390fd5b426006820155600181015460028201546040518581526001600160a01b038581169216907ff930a6e2523c9cc298691873087a740550b8fc85a0680830414c148ed927f6159060200160405180910390a4505050565b6020808201516040808401516060850151608086015160a08701516101008801518551808701875260018152600160fe1b818a0152600554965160009961113299989101611900565b604051602081830303815290604052805190602001209050919050565b82805461115b90611689565b90600052602060002090601f01602090048101928261117d57600085556111c3565b82601f1061119657805160ff19168380011785556111c3565b828001600101855582156111c3579182015b828111156111c35782518255916020019190600101906111a8565b506111cf9291506111d3565b5090565b5b808211156111cf57600081556001016111d4565b6000602082840312156111fa57600080fd5b5035919050565b6001600160a01b038116811461089657600080fd5b60008083601f84011261122857600080fd5b50813567ffffffffffffffff81111561124057600080fd5b60208301915083602082850101111561125857600080fd5b9250929050565b60008060008060008060a0878903121561127857600080fd5b863561128381611201565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff8111156112b457600080fd5b6112c089828a01611216565b979a9699509497509295939492505050565b801515811461089657600080fd5b600080600080600060a086880312156112f857600080fd5b853561130381611201565b94506020860135935060408601359250606086013591506080860135611328816112d2565b809150509295509295909350565b6020808252825182820181905260009190848201906040850190845b8181101561136e57835183529284019291840191600101611352565b50909695505050505050565b6000806000806080858703121561139057600080fd5b84359350602085013592506040850135915060608501356113b0816112d2565b939692955090935050565b803560ff811681146113cc57600080fd5b919050565b6000806000806000806000806000806101208b8d0312156113f157600080fd5b8a356113fc81611201565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff81111561142d57600080fd5b6114398d828e01611216565b90975095505060a08b013561144d81611201565b935061145b60c08c016113bb565b925060e08b013591506101008b013590509295989b9194979a5092959850565b60005b8381101561149657818101518382015260200161147e565b838111156114a5576000848401525b50505050565b600081518084526114c381602086016020860161147b565b601f01601f19169290920160200192915050565b6020815281516020820152602082015160408201526000604083015161150860608401826001600160a01b03169052565b5060608301516001600160a01b038116608084015250608083015160a083015260a083015160c083015260c083015160e083015260e08301516101008181850152808501519150506101208081850152506106046101408401826114ab565b6000806040838503121561157a57600080fd5b823561158581611201565b946020939093013593505050565b600080600080600060a086880312156115ab57600080fd5b8535945060208601356115bd81611201565b93506115cb604087016113bb565b94979396509394606081013594506080013592915050565b6020815260006115f660208301846114ab565b9392505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b600061012060018060a01b03808e1684528c60208501528b60408501528a606085015281608085015261165c8285018a8c6115fd565b971660a0840152505060ff9390931660c084015260e0830191909152610100909101529695505050505050565b600181811c9082168061169d57607f821691505b602082108114156116be57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff811182821017156116fd576116fd6116c4565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561172c5761172c6116c4565b604052919050565b6000602080838503121561174757600080fd5b825167ffffffffffffffff8082111561175f57600080fd5b908401906080828703121561177357600080fd5b61177b6116da565b825181528383015161178c81611201565b81850152604083810151908201526060830151828111156117ac57600080fd5b80840193505086601f8401126117c157600080fd5b8251828111156117d3576117d36116c4565b6117e5601f8201601f19168601611703565b925080835287858286010111156117fb57600080fd5b61180a8186850187870161147b565b50606081019190915295945050505050565b60006020828403121561182e57600080fd5b81516115f6816112d2565b600060018060a01b03808916835260a0602084015261185b60a08401896114ab565b838103604085015261186e81888a6115fd565b6060850196909652509290921660809091015250949350505050565b634e487b7160e01b600052601160045260246000fd5b60006000198214156118b4576118b461188a565b5060010190565b600082198211156118ce576118ce61188a565b500190565b6000828210156118e5576118e561188a565b500390565b634e487b7160e01b600052603260045260246000fd5b88815260006bffffffffffffffffffffffff19808a60601b166020840152808960601b16603484015250866048830152856068830152845161194981608885016020890161147b565b84519083019061196081608884016020890161147b565b016088810193909352505060a80197965050505050505056fea26469706673582212206b83e2d5fb2a34e86903468d36eb72ed8828b1852d24733e2c4f36d7f72717d664736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "attest(address,bytes32,uint256,bytes32,bytes)": { + "details": "Attests to a specific AS.", + "params": { + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The UUID of the new attestation." + } + }, + "attestByDelegation(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)": { + "details": "Attests to a specific AS using a provided EIP712 signature.", + "params": { + "attester": "The attesting account.", + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "r": "The x-coordinate of the nonce R.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "s": "The signature data.", + "schema": "The UUID of the AS.", + "v": "The recovery ID." + }, + "returns": { + "_0": "The UUID of the new attestation." + } + }, + "constructor": { + "details": "Creates a new EAS instance.", + "params": { + "registry": "The address of the global AS registry.", + "verifier": "The address of the EIP712 verifier." + } + }, + "getASRegistry()": { + "details": "Returns the address of the AS global registry.", + "returns": { + "_0": "The address of the AS global registry." + } + }, + "getAttestation(bytes32)": { + "details": "Returns an existing attestation by UUID.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "The attestation data members." + } + }, + "getAttestationsCount()": { + "details": "Returns the global counter for the total number of attestations.", + "returns": { + "_0": "The global counter for the total number of attestations." + } + }, + "getEIP712Verifier()": { + "details": "Returns the address of the EIP712 verifier used to verify signed attestations.", + "returns": { + "_0": "The address of the EIP712 verifier used to verify signed attestations." + } + }, + "getReceivedAttestationUUIDs(address,bytes32,uint256,uint256,bool)": { + "details": "Returns all received attestation UUIDs.", + "params": { + "length": "The number of total members to retrieve.", + "recipient": "The recipient of the attestation.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getReceivedAttestationUUIDsCount(address,bytes32)": { + "details": "Returns the number of received attestation UUIDs.", + "params": { + "recipient": "The recipient of the attestation.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "getRelatedAttestationUUIDs(bytes32,uint256,uint256,bool)": { + "details": "Returns all attestations related to a specific attestation.", + "params": { + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "start": "The offset to start from.", + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getRelatedAttestationUUIDsCount(bytes32)": { + "details": "Returns the number of related attestation UUIDs.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "The number of related attestations." + } + }, + "getSchemaAttestationUUIDs(bytes32,uint256,uint256,bool)": { + "details": "Returns all per-schema attestation UUIDs.", + "params": { + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getSchemaAttestationUUIDsCount(bytes32)": { + "details": "Returns the number of per-schema attestation UUIDs.", + "params": { + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "getSentAttestationUUIDs(address,bytes32,uint256,uint256,bool)": { + "details": "Returns all sent attestation UUIDs.", + "params": { + "attester": "The attesting account.", + "length": "The number of total members to retrieve.", + "reverseOrder": "Whether the offset starts from the end and the data is returned in reverse.", + "schema": "The UUID of the AS.", + "start": "The offset to start from." + }, + "returns": { + "_0": "An array of attestation UUIDs." + } + }, + "getSentAttestationUUIDsCount(address,bytes32)": { + "details": "Returns the number of sent attestation UUIDs.", + "params": { + "recipient": "The recipient of the attestation.", + "schema": "The UUID of the AS." + }, + "returns": { + "_0": "The number of attestations." + } + }, + "isAttestationActive(bytes32)": { + "details": "Checks whether an attestation is active.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "Whether an attestation is active." + } + }, + "isAttestationValid(bytes32)": { + "details": "Checks whether an attestation exists.", + "params": { + "uuid": "The UUID of the attestation to retrieve." + }, + "returns": { + "_0": "Whether an attestation exists." + } + }, + "revoke(bytes32)": { + "details": "Revokes an existing attestation to a specific AS.", + "params": { + "uuid": "The UUID of the attestation to revoke." + } + }, + "revokeByDelegation(bytes32,address,uint8,bytes32,bytes32)": { + "details": "Attests to a specific AS using a provided EIP712 signature.", + "params": { + "attester": "The attesting account.", + "r": "The x-coordinate of the nonce R.", + "s": "The signature data.", + "uuid": "The UUID of the attestation to revoke.", + "v": "The recovery ID." + } + } + }, + "title": "TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 15692, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_relatedAttestations", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + { + "astId": 15699, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_receivedAttestations", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))" + }, + { + "astId": 15706, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_sentAttestations", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))" + }, + { + "astId": 15711, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_schemaAttestations", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + { + "astId": 15716, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_db", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_bytes32,t_struct(Attestation)48372_storage)" + }, + { + "astId": 15718, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_attestationsCount", + "offset": 0, + "slot": "5", + "type": "t_uint256" + }, + { + "astId": 15720, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "_lastUUID", + "offset": 0, + "slot": "6", + "type": "t_bytes32" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "base": "t_bytes32", + "encoding": "dynamic_array", + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(bytes32 => bytes32[]))", + "numberOfBytes": "32", + "value": "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)" + }, + "t_mapping(t_bytes32,t_array(t_bytes32)dyn_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes32[])", + "numberOfBytes": "32", + "value": "t_array(t_bytes32)dyn_storage" + }, + "t_mapping(t_bytes32,t_struct(Attestation)48372_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct IEAS.Attestation)", + "numberOfBytes": "32", + "value": "t_struct(Attestation)48372_storage" + }, + "t_struct(Attestation)48372_storage": { + "encoding": "inplace", + "label": "struct IEAS.Attestation", + "members": [ + { + "astId": 48355, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "uuid", + "offset": 0, + "slot": "0", + "type": "t_bytes32" + }, + { + "astId": 48357, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "schema", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + }, + { + "astId": 48359, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "recipient", + "offset": 0, + "slot": "2", + "type": "t_address" + }, + { + "astId": 48361, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "attester", + "offset": 0, + "slot": "3", + "type": "t_address" + }, + { + "astId": 48363, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "time", + "offset": 0, + "slot": "4", + "type": "t_uint256" + }, + { + "astId": 48365, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "expirationTime", + "offset": 0, + "slot": "5", + "type": "t_uint256" + }, + { + "astId": 48367, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "revocationTime", + "offset": 0, + "slot": "6", + "type": "t_uint256" + }, + { + "astId": 48369, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "refUUID", + "offset": 0, + "slot": "7", + "type": "t_bytes32" + }, + { + "astId": 48371, + "contract": "contracts/EAS/TellerAS.sol:TellerAS", + "label": "data", + "offset": 0, + "slot": "8", + "type": "t_bytes_storage" + } + ], + "numberOfBytes": "288" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/TellerASEIP712Verifier.json b/packages/contracts/deployments/apechain/TellerASEIP712Verifier.json new file mode 100644 index 000000000..ffa83dcda --- /dev/null +++ b/packages/contracts/deployments/apechain/TellerASEIP712Verifier.json @@ -0,0 +1,273 @@ +{ + "address": "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04", + "abi": [ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "InvalidSignature", + "type": "error" + }, + { + "inputs": [], + "name": "ATTEST_TYPEHASH", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DOMAIN_SEPARATOR", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "REVOKE_TYPEHASH", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "internalType": "bytes32", + "name": "schema", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "expirationTime", + "type": "uint256" + }, + { + "internalType": "bytes32", + "name": "refUUID", + "type": "bytes32" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "attest", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "getNonce", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "attester", + "type": "address" + }, + { + "internalType": "uint8", + "name": "v", + "type": "uint8" + }, + { + "internalType": "bytes32", + "name": "r", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "s", + "type": "bytes32" + } + ], + "name": "revoke", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xe7bcbdb0aade6fa1cfcd2383ac81a03033c630cced57f4d851e122d3a99cf839", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xe914D3C7c31395F27D7aeDb29623D1Cb5e1AEf04", + "transactionIndex": 1, + "gasUsed": "451272", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x59923bd861f15adcf443a11be73e8bb4d6468979f52016a04791f8194fde5bb1", + "transactionHash": "0xe7bcbdb0aade6fa1cfcd2383ac81a03033c630cced57f4d851e122d3a99cf839", + "logs": [], + "blockNumber": 33944583, + "cumulativeGasUsed": "451272", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"InvalidSignature\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ATTEST_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DOMAIN_SEPARATOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"REVOKE_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"expirationTime\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"refUUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"attest\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"getNonce\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"revoke\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"attest(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)\":{\"details\":\"Verifies signed attestation.\",\"params\":{\"attester\":\"The attesting account.\",\"data\":\"Additional custom data.\",\"expirationTime\":\"The expiration time of the attestation.\",\"r\":\"The x-coordinate of the nonce R.\",\"recipient\":\"The recipient of the attestation.\",\"refUUID\":\"An optional related attestation's UUID.\",\"s\":\"The signature data.\",\"schema\":\"The UUID of the AS.\",\"v\":\"The recovery ID.\"}},\"constructor\":{\"details\":\"Creates a new EIP712Verifier instance.\"},\"getNonce(address)\":{\"details\":\"Returns the current nonce per-account.\",\"params\":{\"account\":\"The requested accunt.\"},\"returns\":{\"_0\":\"The current nonce.\"}},\"revoke(bytes32,address,uint8,bytes32,bytes32)\":{\"details\":\"Verifies signed revocations.\",\"params\":{\"attester\":\"The attesting account.\",\"r\":\"The x-coordinate of the nonce R.\",\"s\":\"The signature data.\",\"uuid\":\"The UUID of the attestation to revoke.\",\"v\":\"The recovery ID.\"}}},\"title\":\"EIP712 typed signatures verifier for EAS delegated attestations.\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerASEIP712Verifier.sol\":\"TellerASEIP712Verifier\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/EAS/TellerASEIP712Verifier.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\nimport \\\"../interfaces/IEASEIP712Verifier.sol\\\";\\n\\n/**\\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\\n */\\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\\n error InvalidSignature();\\n\\n string public constant VERSION = \\\"0.8\\\";\\n\\n // EIP712 domain separator, making signatures from different domains incompatible.\\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\\n\\n // The hash of the data type used to relay calls to the attest function. It's the value of\\n // keccak256(\\\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\\\").\\n bytes32 public constant ATTEST_TYPEHASH =\\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\\n\\n // The hash of the data type used to relay calls to the revoke function. It's the value of\\n // keccak256(\\\"Revoke(bytes32 uuid,uint256 nonce)\\\").\\n bytes32 public constant REVOKE_TYPEHASH =\\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\\n\\n // Replay protection nonces.\\n mapping(address => uint256) private _nonces;\\n\\n /**\\n * @dev Creates a new EIP712Verifier instance.\\n */\\n constructor() {\\n uint256 chainId;\\n // solhint-disable-next-line no-inline-assembly\\n assembly {\\n chainId := chainid()\\n }\\n\\n DOMAIN_SEPARATOR = keccak256(\\n abi.encode(\\n keccak256(\\n \\\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\\\"\\n ),\\n keccak256(bytes(\\\"EAS\\\")),\\n keccak256(bytes(VERSION)),\\n chainId,\\n address(this)\\n )\\n );\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\n */\\n function getNonce(address account)\\n external\\n view\\n override\\n returns (uint256)\\n {\\n return _nonces[account];\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\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 override {\\n bytes32 digest = keccak256(\\n abi.encodePacked(\\n \\\"\\\\x19\\\\x01\\\",\\n DOMAIN_SEPARATOR,\\n keccak256(\\n abi.encode(\\n ATTEST_TYPEHASH,\\n recipient,\\n schema,\\n expirationTime,\\n refUUID,\\n keccak256(data),\\n _nonces[attester]++\\n )\\n )\\n )\\n );\\n\\n address recoveredAddress = ecrecover(digest, v, r, s);\\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\\n revert InvalidSignature();\\n }\\n }\\n\\n /**\\n * @inheritdoc IEASEIP712Verifier\\n */\\n function revoke(\\n bytes32 uuid,\\n address attester,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external override {\\n bytes32 digest = keccak256(\\n abi.encodePacked(\\n \\\"\\\\x19\\\\x01\\\",\\n DOMAIN_SEPARATOR,\\n keccak256(\\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\\n )\\n )\\n );\\n\\n address recoveredAddress = ecrecover(digest, v, r, s);\\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\\n revert InvalidSignature();\\n }\\n }\\n}\\n\",\"keccak256\":\"0x893f7174a3f30019e37a01b0bfd903caf18125259d13aedbad9212d402c4a4a1\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60a060405234801561001057600080fd5b5060408051808201825260038082526245415360e81b60209283015282518084018452908152620605c760eb1b9082015281517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f818301527f9fed719e0073f95229e6f4f6b6f28f260c524ab08aa40b11f9c28cb710d7c72a818401527f15e7a716d821b9602c70f6d0f574efbb8147fb465215d43354c7b3e69d03ed926060820152466080808301919091523060a0808401919091528451808403909101815260c09092019093528051910120908190526107256101076000396000818160d8015281816101a6015261031a01526107256000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c80636aeb49a51161005b5780636aeb49a5146100fa5780637e4a7d8f1461010d5780638a73222714610134578063ffa1ad741461015b57600080fd5b80631863f01d146100825780632d0335ab146100975780633644e515146100d3575b600080fd5b61009561009036600461051b565b61018a565b005b6100c06100a5366004610569565b6001600160a01b031660009081526020819052604090205490565b6040519081526020015b60405180910390f35b6100c07f000000000000000000000000000000000000000000000000000000000000000081565b61009561010836600461058b565b610316565b6100c07f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147681565b6100c07fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab81565b61017d604051806040016040528060038152602001620605c760eb1b81525081565b6040516100ca9190610661565b6001600160a01b038416600090815260208190526040812080547f0000000000000000000000000000000000000000000000000000000000000000917fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab918991856101f4836106b6565b9091555060408051602081019490945283019190915260608201526080016040516020818303038152906040528051906020012060405160200161024f92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa1580156102ba573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806102ef5750856001600160a01b0316816001600160a01b031614155b1561030d57604051638baa579f60e01b815260040160405180910390fd5b50505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000007f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147660001b8c8c8c8c8c8c6040516103719291906106df565b60408051918290039091206001600160a01b038d1660009081526020819052918220805491926103a0836106b6565b909155506040805160208101989098526001600160a01b03909616958701959095526060860193909352608085019190915260a084015260c083015260e0820152610100016040516020818303038152906040528051906020012060405160200161042292919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa15801561048d573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806104c25750856001600160a01b0316816001600160a01b031614155b156104e057604051638baa579f60e01b815260040160405180910390fd5b505050505050505050505050565b80356001600160a01b038116811461050557600080fd5b919050565b803560ff8116811461050557600080fd5b600080600080600060a0868803121561053357600080fd5b85359450610543602087016104ee565b93506105516040870161050a565b94979396509394606081013594506080013592915050565b60006020828403121561057b57600080fd5b610584826104ee565b9392505050565b6000806000806000806000806000806101208b8d0312156105ab57600080fd5b6105b48b6104ee565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff808211156105e657600080fd5b818d0191508d601f8301126105fa57600080fd5b81358181111561060957600080fd5b8e602082850101111561061b57600080fd5b60208301985080975050505061063360a08c016104ee565b935061064160c08c0161050a565b925060e08b013591506101008b013590509295989b9194979a5092959850565b600060208083528351808285015260005b8181101561068e57858101830151858201604001528201610672565b818111156106a0576000604083870101525b50601f01601f1916929092016040019392505050565b60006000198214156106d857634e487b7160e01b600052601160045260246000fd5b5060010190565b818382376000910190815291905056fea2646970667358221220d0c93b24e391671ef66b1f903855bc7ab981d375fc65451171489c87152dff3364736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061007d5760003560e01c80636aeb49a51161005b5780636aeb49a5146100fa5780637e4a7d8f1461010d5780638a73222714610134578063ffa1ad741461015b57600080fd5b80631863f01d146100825780632d0335ab146100975780633644e515146100d3575b600080fd5b61009561009036600461051b565b61018a565b005b6100c06100a5366004610569565b6001600160a01b031660009081526020819052604090205490565b6040519081526020015b60405180910390f35b6100c07f000000000000000000000000000000000000000000000000000000000000000081565b61009561010836600461058b565b610316565b6100c07f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147681565b6100c07fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab81565b61017d604051806040016040528060038152602001620605c760eb1b81525081565b6040516100ca9190610661565b6001600160a01b038416600090815260208190526040812080547f0000000000000000000000000000000000000000000000000000000000000000917fbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab918991856101f4836106b6565b9091555060408051602081019490945283019190915260608201526080016040516020818303038152906040528051906020012060405160200161024f92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa1580156102ba573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806102ef5750856001600160a01b0316816001600160a01b031614155b1561030d57604051638baa579f60e01b815260040160405180910390fd5b50505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000007f39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d147660001b8c8c8c8c8c8c6040516103719291906106df565b60408051918290039091206001600160a01b038d1660009081526020819052918220805491926103a0836106b6565b909155506040805160208101989098526001600160a01b03909616958701959095526060860193909352608085019190915260a084015260c083015260e0820152610100016040516020818303038152906040528051906020012060405160200161042292919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa15801561048d573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615806104c25750856001600160a01b0316816001600160a01b031614155b156104e057604051638baa579f60e01b815260040160405180910390fd5b505050505050505050505050565b80356001600160a01b038116811461050557600080fd5b919050565b803560ff8116811461050557600080fd5b600080600080600060a0868803121561053357600080fd5b85359450610543602087016104ee565b93506105516040870161050a565b94979396509394606081013594506080013592915050565b60006020828403121561057b57600080fd5b610584826104ee565b9392505050565b6000806000806000806000806000806101208b8d0312156105ab57600080fd5b6105b48b6104ee565b995060208b0135985060408b0135975060608b0135965060808b013567ffffffffffffffff808211156105e657600080fd5b818d0191508d601f8301126105fa57600080fd5b81358181111561060957600080fd5b8e602082850101111561061b57600080fd5b60208301985080975050505061063360a08c016104ee565b935061064160c08c0161050a565b925060e08b013591506101008b013590509295989b9194979a5092959850565b600060208083528351808285015260005b8181101561068e57858101830151858201604001528201610672565b818111156106a0576000604083870101525b50601f01601f1916929092016040019392505050565b60006000198214156106d857634e487b7160e01b600052601160045260246000fd5b5060010190565b818382376000910190815291905056fea2646970667358221220d0c93b24e391671ef66b1f903855bc7ab981d375fc65451171489c87152dff3364736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "attest(address,bytes32,uint256,bytes32,bytes,address,uint8,bytes32,bytes32)": { + "details": "Verifies signed attestation.", + "params": { + "attester": "The attesting account.", + "data": "Additional custom data.", + "expirationTime": "The expiration time of the attestation.", + "r": "The x-coordinate of the nonce R.", + "recipient": "The recipient of the attestation.", + "refUUID": "An optional related attestation's UUID.", + "s": "The signature data.", + "schema": "The UUID of the AS.", + "v": "The recovery ID." + } + }, + "constructor": { + "details": "Creates a new EIP712Verifier instance." + }, + "getNonce(address)": { + "details": "Returns the current nonce per-account.", + "params": { + "account": "The requested accunt." + }, + "returns": { + "_0": "The current nonce." + } + }, + "revoke(bytes32,address,uint8,bytes32,bytes32)": { + "details": "Verifies signed revocations.", + "params": { + "attester": "The attesting account.", + "r": "The x-coordinate of the nonce R.", + "s": "The signature data.", + "uuid": "The UUID of the attestation to revoke.", + "v": "The recovery ID." + } + } + }, + "title": "EIP712 typed signatures verifier for EAS delegated attestations.", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 16574, + "contract": "contracts/EAS/TellerASEIP712Verifier.sol:TellerASEIP712Verifier", + "label": "_nonces", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_uint256)" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_uint256)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/TellerASRegistry.json b/packages/contracts/deployments/apechain/TellerASRegistry.json new file mode 100644 index 000000000..0c1aee4cc --- /dev/null +++ b/packages/contracts/deployments/apechain/TellerASRegistry.json @@ -0,0 +1,285 @@ +{ + "address": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", + "abi": [ + { + "inputs": [], + "name": "AlreadyExists", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "schema", + "type": "bytes" + }, + { + "indexed": false, + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "attester", + "type": "address" + } + ], + "name": "Registered", + "type": "event" + }, + { + "inputs": [], + "name": "VERSION", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + } + ], + "name": "getAS", + "outputs": [ + { + "components": [ + { + "internalType": "bytes32", + "name": "uuid", + "type": "bytes32" + }, + { + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + }, + { + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "schema", + "type": "bytes" + } + ], + "internalType": "struct IASRegistry.ASRecord", + "name": "", + "type": "tuple" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getASCount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "schema", + "type": "bytes" + }, + { + "internalType": "contract IASResolver", + "name": "resolver", + "type": "address" + } + ], + "name": "register", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x4f38212b0bf493d3e378ec3fdebaf60f712438912ed04dd110bdf0fa056aa56d", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x28940408c1aD15f81f77D8C0Ed2A45B8e19e7147", + "transactionIndex": 1, + "gasUsed": "415687", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xc95788a4d2e40ee637588372f44ae5c992679a69a8dfa2b5303ffb3d8d68093e", + "transactionHash": "0x4f38212b0bf493d3e378ec3fdebaf60f712438912ed04dd110bdf0fa056aa56d", + "logs": [], + "blockNumber": 33944579, + "cumulativeGasUsed": "415687", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"name\":\"AlreadyExists\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"attester\",\"type\":\"address\"}],\"name\":\"Registered\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"}],\"name\":\"getAS\",\"outputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"uuid\",\"type\":\"bytes32\"},{\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"}],\"internalType\":\"struct IASRegistry.ASRecord\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getASCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"schema\",\"type\":\"bytes\"},{\"internalType\":\"contract IASResolver\",\"name\":\"resolver\",\"type\":\"address\"}],\"name\":\"register\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"getAS(bytes32)\":{\"details\":\"Returns an existing AS by UUID\",\"params\":{\"uuid\":\"The UUID of the AS to retrieve.\"},\"returns\":{\"_0\":\"The AS data members.\"}},\"getASCount()\":{\"details\":\"Returns the global counter for the total number of attestations\",\"returns\":{\"_0\":\"The global counter for the total number of attestations.\"}},\"register(bytes,address)\":{\"details\":\"Submits and reserve a new AS\",\"params\":{\"resolver\":\"An optional AS schema resolver.\",\"schema\":\"The AS data schema.\"},\"returns\":{\"_0\":\"The UUID of the new AS.\"}}},\"title\":\"The global AS registry.\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/EAS/TellerASRegistry.sol\":\"TellerASRegistry\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/EAS/TellerASRegistry.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\nimport \\\"../Types.sol\\\";\\nimport \\\"../interfaces/IASRegistry.sol\\\";\\nimport \\\"../interfaces/IASResolver.sol\\\";\\n\\n/**\\n * @title The global AS registry.\\n */\\ncontract TellerASRegistry is IASRegistry {\\n error AlreadyExists();\\n\\n string public constant VERSION = \\\"0.8\\\";\\n\\n // The global mapping between AS records and their IDs.\\n mapping(bytes32 => ASRecord) private _registry;\\n\\n // The global counter for the total number of attestations.\\n uint256 private _asCount;\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function register(bytes calldata schema, IASResolver resolver)\\n external\\n override\\n returns (bytes32)\\n {\\n uint256 index = ++_asCount;\\n\\n ASRecord memory asRecord = ASRecord({\\n uuid: EMPTY_UUID,\\n index: index,\\n schema: schema,\\n resolver: resolver\\n });\\n\\n bytes32 uuid = _getUUID(asRecord);\\n if (_registry[uuid].uuid != EMPTY_UUID) {\\n revert AlreadyExists();\\n }\\n\\n asRecord.uuid = uuid;\\n _registry[uuid] = asRecord;\\n\\n emit Registered(uuid, index, schema, resolver, msg.sender);\\n\\n return uuid;\\n }\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function getAS(bytes32 uuid)\\n external\\n view\\n override\\n returns (ASRecord memory)\\n {\\n return _registry[uuid];\\n }\\n\\n /**\\n * @inheritdoc IASRegistry\\n */\\n function getASCount() external view override returns (uint256) {\\n return _asCount;\\n }\\n\\n /**\\n * @dev Calculates a UUID for a given AS.\\n *\\n * @param asRecord The input AS.\\n *\\n * @return AS UUID.\\n */\\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\\n }\\n}\\n\",\"keccak256\":\"0x1d5782c3bb5ea52db95c8ce6d7ff6d20382bae8ca574614cfbaa45c05f93f13c\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b5061068e806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806372487d5214610051578063a99e7e291461007a578063d96250641461009b578063ffa1ad74146100a3575b600080fd5b61006461005f36600461040f565b6100d2565b6040516100719190610484565b60405180910390f35b61008d6100883660046104cd565b6101d3565b604051908152602001610071565b60015461008d565b6100c5604051806040016040528060038152602001620605c760eb1b81525081565b604051610071919061055c565b60408051608081018252600080825260208201819052918101919091526060808201526000828152602081815260409182902082516080810184528154815260018201546001600160a01b03169281019290925260028101549282019290925260038201805491929160608401919061014a90610576565b80601f016020809104026020016040519081016040528092919081815260200182805461017690610576565b80156101c35780601f10610198576101008083540402835291602001916101c3565b820191906000526020600020905b8154815290600101906020018083116101a657829003601f168201915b5050505050815250509050919050565b6000806001600081546101e5906105b1565b9190508190559050600060405180608001604052806000801b8152602001856001600160a01b0316815260200183815260200187878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350915061025f90508261033c565b6000818152602081905260409020549091501561028f5760405163119b4fd360e11b815260040160405180910390fd5b8082526000818152602081815260409182902084518155818501516001820180546001600160a01b0319166001600160a01b03909216919091179055918401516002830155606084015180518593926102ef926003850192910190610376565b5090505082817f51a1a037ef8a642f8b5528429785b5a54e6ee54fb2d2db4b4a44480b5302d55b8989893360405161032a94939291906105da565b60405180910390a39695505050505050565b600081606001518260200151604051602001610359929190610621565b604051602081830303815290604052805190602001209050919050565b82805461038290610576565b90600052602060002090601f0160209004810192826103a457600085556103ea565b82601f106103bd57805160ff19168380011785556103ea565b828001600101855582156103ea579182015b828111156103ea5782518255916020019190600101906103cf565b506103f69291506103fa565b5090565b5b808211156103f657600081556001016103fb565b60006020828403121561042157600080fd5b5035919050565b60005b8381101561044357818101518382015260200161042b565b83811115610452576000848401525b50505050565b60008151808452610470816020860160208601610428565b601f01601f19169290920160200192915050565b602081528151602082015260018060a01b03602083015116604082015260408201516060820152600060608301516080808401526104c560a0840182610458565b949350505050565b6000806000604084860312156104e257600080fd5b833567ffffffffffffffff808211156104fa57600080fd5b818601915086601f83011261050e57600080fd5b81358181111561051d57600080fd5b87602082850101111561052f57600080fd5b602092830195509350508401356001600160a01b038116811461055157600080fd5b809150509250925092565b60208152600061056f6020830184610458565b9392505050565b600181811c9082168061058a57607f821691505b602082108114156105ab57634e487b7160e01b600052602260045260246000fd5b50919050565b60006000198214156105d357634e487b7160e01b600052601160045260246000fd5b5060010190565b6060815283606082015283856080830137600060808583018101919091526001600160a01b039384166020830152919092166040830152601f909201601f19160101919050565b60008351610633818460208801610428565b60609390931b6bffffffffffffffffffffffff1916919092019081526014019291505056fea2646970667358221220f4080119bbc4198852f1eee79e8e0c663b8e4189faee0f706f0d5bbdbec3e88a64736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061004c5760003560e01c806372487d5214610051578063a99e7e291461007a578063d96250641461009b578063ffa1ad74146100a3575b600080fd5b61006461005f36600461040f565b6100d2565b6040516100719190610484565b60405180910390f35b61008d6100883660046104cd565b6101d3565b604051908152602001610071565b60015461008d565b6100c5604051806040016040528060038152602001620605c760eb1b81525081565b604051610071919061055c565b60408051608081018252600080825260208201819052918101919091526060808201526000828152602081815260409182902082516080810184528154815260018201546001600160a01b03169281019290925260028101549282019290925260038201805491929160608401919061014a90610576565b80601f016020809104026020016040519081016040528092919081815260200182805461017690610576565b80156101c35780601f10610198576101008083540402835291602001916101c3565b820191906000526020600020905b8154815290600101906020018083116101a657829003601f168201915b5050505050815250509050919050565b6000806001600081546101e5906105b1565b9190508190559050600060405180608001604052806000801b8152602001856001600160a01b0316815260200183815260200187878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350915061025f90508261033c565b6000818152602081905260409020549091501561028f5760405163119b4fd360e11b815260040160405180910390fd5b8082526000818152602081815260409182902084518155818501516001820180546001600160a01b0319166001600160a01b03909216919091179055918401516002830155606084015180518593926102ef926003850192910190610376565b5090505082817f51a1a037ef8a642f8b5528429785b5a54e6ee54fb2d2db4b4a44480b5302d55b8989893360405161032a94939291906105da565b60405180910390a39695505050505050565b600081606001518260200151604051602001610359929190610621565b604051602081830303815290604052805190602001209050919050565b82805461038290610576565b90600052602060002090601f0160209004810192826103a457600085556103ea565b82601f106103bd57805160ff19168380011785556103ea565b828001600101855582156103ea579182015b828111156103ea5782518255916020019190600101906103cf565b506103f69291506103fa565b5090565b5b808211156103f657600081556001016103fb565b60006020828403121561042157600080fd5b5035919050565b60005b8381101561044357818101518382015260200161042b565b83811115610452576000848401525b50505050565b60008151808452610470816020860160208601610428565b601f01601f19169290920160200192915050565b602081528151602082015260018060a01b03602083015116604082015260408201516060820152600060608301516080808401526104c560a0840182610458565b949350505050565b6000806000604084860312156104e257600080fd5b833567ffffffffffffffff808211156104fa57600080fd5b818601915086601f83011261050e57600080fd5b81358181111561051d57600080fd5b87602082850101111561052f57600080fd5b602092830195509350508401356001600160a01b038116811461055157600080fd5b809150509250925092565b60208152600061056f6020830184610458565b9392505050565b600181811c9082168061058a57607f821691505b602082108114156105ab57634e487b7160e01b600052602260045260246000fd5b50919050565b60006000198214156105d357634e487b7160e01b600052601160045260246000fd5b5060010190565b6060815283606082015283856080830137600060808583018101919091526001600160a01b039384166020830152919092166040830152601f909201601f19160101919050565b60008351610633818460208801610428565b60609390931b6bffffffffffffffffffffffff1916919092019081526014019291505056fea2646970667358221220f4080119bbc4198852f1eee79e8e0c663b8e4189faee0f706f0d5bbdbec3e88a64736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "getAS(bytes32)": { + "details": "Returns an existing AS by UUID", + "params": { + "uuid": "The UUID of the AS to retrieve." + }, + "returns": { + "_0": "The AS data members." + } + }, + "getASCount()": { + "details": "Returns the global counter for the total number of attestations", + "returns": { + "_0": "The global counter for the total number of attestations." + } + }, + "register(bytes,address)": { + "details": "Submits and reserve a new AS", + "params": { + "resolver": "An optional AS schema resolver.", + "schema": "The AS data schema." + }, + "returns": { + "_0": "The UUID of the new AS." + } + } + }, + "title": "The global AS registry.", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 16780, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "_registry", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(ASRecord)48152_storage)" + }, + { + "astId": 16782, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "_asCount", + "offset": 0, + "slot": "1", + "type": "t_uint256" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_contract(IASResolver)48219": { + "encoding": "inplace", + "label": "contract IASResolver", + "numberOfBytes": "20" + }, + "t_mapping(t_bytes32,t_struct(ASRecord)48152_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct IASRegistry.ASRecord)", + "numberOfBytes": "32", + "value": "t_struct(ASRecord)48152_storage" + }, + "t_struct(ASRecord)48152_storage": { + "encoding": "inplace", + "label": "struct IASRegistry.ASRecord", + "members": [ + { + "astId": 48144, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "uuid", + "offset": 0, + "slot": "0", + "type": "t_bytes32" + }, + { + "astId": 48147, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "resolver", + "offset": 0, + "slot": "1", + "type": "t_contract(IASResolver)48219" + }, + { + "astId": 48149, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "index", + "offset": 0, + "slot": "2", + "type": "t_uint256" + }, + { + "astId": 48151, + "contract": "contracts/EAS/TellerASRegistry.sol:TellerASRegistry", + "label": "schema", + "offset": 0, + "slot": "3", + "type": "t_bytes_storage" + } + ], + "numberOfBytes": "128" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/TellerV2.json b/packages/contracts/deployments/apechain/TellerV2.json new file mode 100644 index 000000000..cb83cf053 --- /dev/null +++ b/packages/contracts/deployments/apechain/TellerV2.json @@ -0,0 +1,1761 @@ +{ + "address": "0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "trustedForwarder" + } + ] + }, + { + "type": "error", + "name": "ActionNotAllowed", + "inputs": [ + { + "type": "uint256", + "name": "bidId" + }, + { + "type": "string", + "name": "action" + }, + { + "type": "string", + "name": "message" + } + ] + }, + { + "type": "error", + "name": "PaymentNotMinimum", + "inputs": [ + { + "type": "uint256", + "name": "bidId" + }, + { + "type": "uint256", + "name": "payment" + }, + { + "type": "uint256", + "name": "minimumOwed" + } + ] + }, + { + "type": "error", + "name": "SafeERC20FailedOperation", + "inputs": [ + { + "type": "address", + "name": "token" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "AcceptedBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "lender", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CancelledBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "FeePaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "string", + "name": "feeType", + "indexed": true + }, + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanClosed", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepayment", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketForwarderApproved", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": true + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketForwarderRenounced", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": true + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "MarketOwnerCancelledBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ProtocolFeeSet", + "inputs": [ + { + "type": "uint16", + "name": "newFee", + "indexed": false + }, + { + "type": "uint16", + "name": "oldFee", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SubmittedBid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": false + }, + { + "type": "bytes32", + "name": "metadataURI", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "TrustedMarketForwarderSet", + "inputs": [ + { + "type": "uint256", + "name": "marketId", + "indexed": true + }, + { + "type": "address", + "name": "forwarder", + "indexed": false + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "function", + "name": "CURRENT_CODE_VERSION", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "LIQUIDATION_DELAY", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "__lenderVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "__totalVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approveMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "bidDefaultDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidExpirationTime", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bidPaymentCycleType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "bids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketplaceId" + }, + { + "type": "bytes32", + "name": "_metadataURI" + }, + { + "type": "tuple", + "name": "loanDetails", + "components": [ + { + "type": "address", + "name": "lendingToken" + }, + { + "type": "uint256", + "name": "principal" + }, + { + "type": "tuple", + "name": "totalRepaid", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + }, + { + "type": "uint32", + "name": "timestamp" + }, + { + "type": "uint32", + "name": "acceptedTimestamp" + }, + { + "type": "uint32", + "name": "lastRepaidTimestamp" + }, + { + "type": "uint32", + "name": "loanDuration" + } + ] + }, + { + "type": "tuple", + "name": "terms", + "components": [ + { + "type": "uint256", + "name": "paymentCycleAmount" + }, + { + "type": "uint32", + "name": "paymentCycle" + }, + { + "type": "uint16", + "name": "APR" + } + ] + }, + { + "type": "uint8", + "name": "state" + }, + { + "type": "uint8", + "name": "paymentType" + } + ] + }, + { + "type": "function", + "name": "borrowerBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateAmountDue", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "tuple", + "name": "due", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + } + ] + }, + { + "type": "function", + "name": "calculateAmountOwed", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_timestamp" + } + ], + "outputs": [ + { + "type": "tuple", + "name": "owed", + "components": [ + { + "type": "uint256", + "name": "principal" + }, + { + "type": "uint256", + "name": "interest" + } + ] + } + ] + }, + { + "type": "function", + "name": "calculateNextDueDate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "dueDate_" + } + ] + }, + { + "type": "function", + "name": "cancelBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "claimLoanNFT", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "collateralManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "escrowVault", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBidState", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBorrowerActiveLoanIds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getBorrowerLoanIds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + } + ], + "outputs": [ + { + "type": "uint256[]", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getEscrowVault", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLoanBorrower", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower_" + } + ] + }, + { + "type": "function", + "name": "getLoanDefaultTimestamp", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLoanLender", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "lender_" + } + ] + }, + { + "type": "function", + "name": "getLoanLendingToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "token_" + } + ] + }, + { + "type": "function", + "name": "getLoanMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "_marketId" + } + ] + }, + { + "type": "function", + "name": "getLoanSummary", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "borrower" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint32", + "name": "acceptedTimestamp" + }, + { + "type": "uint32", + "name": "lastRepaidTimestamp" + }, + { + "type": "uint8", + "name": "bidState" + } + ] + }, + { + "type": "function", + "name": "getProtocolFeeRecipient", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getProtocolPausingManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getRepaymentListenerForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "hasApprovedMarketForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + }, + { + "type": "address", + "name": "_account" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "_protocolFee" + }, + { + "type": "address", + "name": "_marketRegistry" + }, + { + "type": "address", + "name": "_reputationManager" + }, + { + "type": "address", + "name": "_lenderCommitmentForwarder" + }, + { + "type": "address", + "name": "_collateralManager" + }, + { + "type": "address", + "name": "_lenderManager" + }, + { + "type": "address", + "name": "_escrowVault" + }, + { + "type": "address", + "name": "_protocolPausingManager" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "isLoanDefaulted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isLoanExpired", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isLoanLiquidateable", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isPaymentLate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isTrustedForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "forwarder" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "isTrustedMarketForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_trustedMarketForwarder" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastRepaidTimestamp", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "amountToProtocol" + }, + { + "type": "uint256", + "name": "amountToMarketplace" + }, + { + "type": "uint256", + "name": "amountToBorrower" + } + ] + }, + { + "type": "function", + "name": "lenderCloseLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderCloseLoanWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_collateralRecipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderCommitmentForwarder", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lenderVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + }, + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateLoanFull", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidateLoanFullWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketOwnerCancelBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "marketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "protocolFee", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoan", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanFull", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanFullWithoutCollateralWithdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanMinimum", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanWithoutCollateralWithdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "repaymentListenerForBid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "reputationManager", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "setProtocolFee", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint16", + "name": "newFee" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setProtocolFeeRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_recipient" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setRepaymentListenerForBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "_listener" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setTrustedMarketForwarder", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_marketId" + }, + { + "type": "address", + "name": "_forwarder" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "submitBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lendingToken" + }, + { + "type": "uint256", + "name": "_marketplaceId" + }, + { + "type": "uint256", + "name": "_principal" + }, + { + "type": "uint32", + "name": "_duration" + }, + { + "type": "uint16", + "name": "_APR" + }, + { + "type": "string", + "name": "_metadataURI" + }, + { + "type": "address", + "name": "_receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId_" + } + ] + }, + { + "type": "function", + "name": "submitBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lendingToken" + }, + { + "type": "uint256", + "name": "_marketplaceId" + }, + { + "type": "uint256", + "name": "_principal" + }, + { + "type": "uint32", + "name": "_duration" + }, + { + "type": "uint16", + "name": "_APR" + }, + { + "type": "string", + "name": "_metadataURI" + }, + { + "type": "address", + "name": "_receiver" + }, + { + "type": "tuple[]", + "name": "_collateralInfo", + "components": [ + { + "type": "uint8", + "name": "_collateralType" + }, + { + "type": "uint256", + "name": "_amount" + }, + { + "type": "uint256", + "name": "_tokenId" + }, + { + "type": "address", + "name": "_collateralAddress" + } + ] + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId_" + } + ] + }, + { + "type": "function", + "name": "totalVolumeFilled", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "uris", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "version", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + } + ], + "transactionHash": "0xa84d0bf1f91dea76a6849b3eb32c9a90ec2cb0f8e5a79bf138785583003537b8", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0x3a48936c4a786bdf2e927f6bf8d5fc1c58a87e1c8ce623ef1e91a3eadb7b2b6a", + "blockNumber": 33944573 + }, + "numDeployments": 1, + "implementation": "0xE11884953B18F8ddC55875CBDAb71b624779D3bB" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/TimelockController.json b/packages/contracts/deployments/apechain/TimelockController.json new file mode 100644 index 000000000..288b0cb24 --- /dev/null +++ b/packages/contracts/deployments/apechain/TimelockController.json @@ -0,0 +1,1246 @@ +{ + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "minDelay", + "type": "uint256" + }, + { + "internalType": "address[]", + "name": "proposers", + "type": "address[]" + }, + { + "internalType": "address[]", + "name": "executors", + "type": "address[]" + }, + { + "internalType": "address", + "name": "admin", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "CallExecuted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "index", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "CallScheduled", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "Cancelled", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldDuration", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newDuration", + "type": "uint256" + } + ], + "name": "MinDelayChange", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "previousAdminRole", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "bytes32", + "name": "newAdminRole", + "type": "bytes32" + } + ], + "name": "RoleAdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleGranted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "indexed": true, + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + } + ], + "name": "RoleRevoked", + "type": "event" + }, + { + "inputs": [], + "name": "CANCELLER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "DEFAULT_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "EXECUTOR_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "PROPOSER_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "TIMELOCK_ADMIN_ROLE", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "cancel", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "payload", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "execute", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "executeBatch", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [], + "name": "getMinDelay", + "outputs": [ + { + "internalType": "uint256", + "name": "duration", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + } + ], + "name": "getRoleAdmin", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "getTimestamp", + "outputs": [ + { + "internalType": "uint256", + "name": "timestamp", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "grantRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "hasRole", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "hashOperation", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + } + ], + "name": "hashOperationBatch", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperation", + "outputs": [ + { + "internalType": "bool", + "name": "registered", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationDone", + "outputs": [ + { + "internalType": "bool", + "name": "done", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationPending", + "outputs": [ + { + "internalType": "bool", + "name": "pending", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "id", + "type": "bytes32" + } + ], + "name": "isOperationReady", + "outputs": [ + { + "internalType": "bool", + "name": "ready", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256[]", + "name": "", + "type": "uint256[]" + }, + { + "internalType": "uint256[]", + "name": "", + "type": "uint256[]" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155BatchReceived", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC721Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "renounceRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "role", + "type": "bytes32" + }, + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "revokeRole", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "schedule", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "targets", + "type": "address[]" + }, + { + "internalType": "uint256[]", + "name": "values", + "type": "uint256[]" + }, + { + "internalType": "bytes[]", + "name": "payloads", + "type": "bytes[]" + }, + { + "internalType": "bytes32", + "name": "predecessor", + "type": "bytes32" + }, + { + "internalType": "bytes32", + "name": "salt", + "type": "bytes32" + }, + { + "internalType": "uint256", + "name": "delay", + "type": "uint256" + } + ], + "name": "scheduleBatch", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes4", + "name": "interfaceId", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newDelay", + "type": "uint256" + } + ], + "name": "updateDelay", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ], + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "transactionIndex": 1, + "gasUsed": "1966959", + "logsBloom": "0x000000040000000008020000000000000a0000000000000000000000000000000000000000000040000000000001000000000000000000000200040010200000000000000000000000040010000000000000000000000000000000000001000000000000020000400000000000100800000000000000000000020000000000000000000000000000000000000000000000000000001200080000000000000000000000000020400000000000000000000000000000000000001002000000000000000000000000004000000000000000000600000000000100000100200020000400000000001200000000000000000000000000000000000000000000000000", + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148", + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "logs": [ + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 0, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 1, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 2, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff", + "0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5" + ], + "data": "0x", + "logIndex": 3, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x0000000000000000000000006b1ec259a35005b7562c92f42c490f39131ff1d8", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 4, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5", + "0x0000000000000000000000002bbd69c72b6689f31dd12b93ff59e62632e0ef41", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 5, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1", + "0x0000000000000000000000002bbd69c72b6689f31dd12b93ff59e62632e0ef41", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 6, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "0x0000000000000000000000002bbd69c72b6689f31dd12b93ff59e62632e0ef41", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 7, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", + "0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63", + "0x0000000000000000000000002bbd69c72b6689f31dd12b93ff59e62632e0ef41", + "0x000000000000000000000000d9b023522cece02251d877bb0eb4f06fde6f98e6" + ], + "data": "0x", + "logIndex": 8, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + }, + { + "transactionIndex": 1, + "blockNumber": 33944562, + "transactionHash": "0x3227357d42875926f93439d265f815b540bcbb10468855b72b4427aeab0932e8", + "address": "0x6b1eC259a35005b7562c92f42C490f39131fF1d8", + "topics": [ + "0x11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4", + "logIndex": 9, + "blockHash": "0x5c5f2a18aa6ea4b2cbec28401b13ade27100822a27761f84d0ad0fcb9308f148" + } + ], + "blockNumber": 33944562, + "cumulativeGasUsed": "1966959", + "status": 1, + "byzantium": true + }, + "args": [ + 180, + [ + "0x2BbD69C72b6689F31dd12b93fF59E62632E0eF41" + ], + [ + "0x2BbD69C72b6689F31dd12b93fF59E62632E0eF41" + ], + "0x2BbD69C72b6689F31dd12b93fF59E62632E0eF41" + ], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"minDelay\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"proposers\",\"type\":\"address[]\"},{\"internalType\":\"address[]\",\"name\":\"executors\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"admin\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"CallExecuted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"CallScheduled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"Cancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"oldDuration\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"newDuration\",\"type\":\"uint256\"}],\"name\":\"MinDelayChange\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"previousAdminRole\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"newAdminRole\",\"type\":\"bytes32\"}],\"name\":\"RoleAdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleGranted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"RoleRevoked\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CANCELLER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DEFAULT_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"EXECUTOR_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PROPOSER_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"TIMELOCK_ADMIN_ROLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"cancel\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"payload\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"execute\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"executeBatch\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getMinDelay\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"duration\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"}],\"name\":\"getRoleAdmin\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"getTimestamp\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"timestamp\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"grantRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"hasRole\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"hashOperation\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"}],\"name\":\"hashOperationBatch\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperation\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"registered\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationDone\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"done\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationPending\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"pending\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"id\",\"type\":\"bytes32\"}],\"name\":\"isOperationReady\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"ready\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155BatchReceived\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC721Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"renounceRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"role\",\"type\":\"bytes32\"},{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"revokeRole\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"schedule\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"targets\",\"type\":\"address[]\"},{\"internalType\":\"uint256[]\",\"name\":\"values\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes[]\",\"name\":\"payloads\",\"type\":\"bytes[]\"},{\"internalType\":\"bytes32\",\"name\":\"predecessor\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"salt\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"delay\",\"type\":\"uint256\"}],\"name\":\"scheduleBatch\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"newDelay\",\"type\":\"uint256\"}],\"name\":\"updateDelay\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied. By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer. _Available since v3.3._\",\"events\":{\"CallExecuted(bytes32,uint256,address,uint256,bytes)\":{\"details\":\"Emitted when a call is performed as part of operation `id`.\"},\"CallScheduled(bytes32,uint256,address,uint256,bytes,bytes32,uint256)\":{\"details\":\"Emitted when a call is scheduled as part of operation `id`.\"},\"Cancelled(bytes32)\":{\"details\":\"Emitted when operation `id` is cancelled.\"},\"MinDelayChange(uint256,uint256)\":{\"details\":\"Emitted when the minimum delay for future operations is modified.\"}},\"kind\":\"dev\",\"methods\":{\"cancel(bytes32)\":{\"details\":\"Cancel an operation. Requirements: - the caller must have the 'canceller' role.\"},\"constructor\":{\"details\":\"Initializes the contract with the following parameters: - `minDelay`: initial minimum delay for operations - `proposers`: accounts to be granted proposer and canceller roles - `executors`: accounts to be granted executor role - `admin`: optional account to be granted admin role; disable with zero address IMPORTANT: The optional admin can aid with initial configuration of roles after deployment without being subject to delay, but this role should be subsequently renounced in favor of administration through timelocked proposals. Previous versions of this contract would assign this admin to the deployer automatically and should be renounced as well.\"},\"execute(address,uint256,bytes,bytes32,bytes32)\":{\"details\":\"Execute an (ready) operation containing a single transaction. Emits a {CallExecuted} event. Requirements: - the caller must have the 'executor' role.\"},\"executeBatch(address[],uint256[],bytes[],bytes32,bytes32)\":{\"details\":\"Execute an (ready) operation containing a batch of transactions. Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' role.\"},\"getMinDelay()\":{\"details\":\"Returns the minimum delay for an operation to become valid. This value can be changed by executing an operation that calls `updateDelay`.\"},\"getRoleAdmin(bytes32)\":{\"details\":\"Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}.\"},\"getTimestamp(bytes32)\":{\"details\":\"Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations).\"},\"grantRole(bytes32,address)\":{\"details\":\"Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event.\"},\"hasRole(bytes32,address)\":{\"details\":\"Returns `true` if `account` has been granted `role`.\"},\"hashOperation(address,uint256,bytes,bytes32,bytes32)\":{\"details\":\"Returns the identifier of an operation containing a single transaction.\"},\"hashOperationBatch(address[],uint256[],bytes[],bytes32,bytes32)\":{\"details\":\"Returns the identifier of an operation containing a batch of transactions.\"},\"isOperation(bytes32)\":{\"details\":\"Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations.\"},\"isOperationDone(bytes32)\":{\"details\":\"Returns whether an operation is done or not.\"},\"isOperationPending(bytes32)\":{\"details\":\"Returns whether an operation is pending or not.\"},\"isOperationReady(bytes32)\":{\"details\":\"Returns whether an operation is ready or not.\"},\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\":{\"details\":\"See {IERC1155Receiver-onERC1155BatchReceived}.\"},\"onERC1155Received(address,address,uint256,uint256,bytes)\":{\"details\":\"See {IERC1155Receiver-onERC1155Received}.\"},\"onERC721Received(address,address,uint256,bytes)\":{\"details\":\"See {IERC721Receiver-onERC721Received}.\"},\"renounceRole(bytes32,address)\":{\"details\":\"Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event.\"},\"revokeRole(bytes32,address)\":{\"details\":\"Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event.\"},\"schedule(address,uint256,bytes,bytes32,bytes32,uint256)\":{\"details\":\"Schedule an operation containing a single transaction. Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role.\"},\"scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256)\":{\"details\":\"Schedule an operation containing a batch of transactions. Emits one {CallScheduled} event per transaction in the batch. Requirements: - the caller must have the 'proposer' role.\"},\"supportsInterface(bytes4)\":{\"details\":\"See {IERC165-supportsInterface}.\"},\"updateDelay(uint256)\":{\"details\":\"Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/admin/TimelockController.sol\":\"TimelockController\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/admin/TimelockController.sol\":{\"content\":\"/**\\n *Submitted for verification at Etherscan.io on 2023-02-08\\n*/\\n\\n//SPDX-License-Identifier: MIT\\n\\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev External interface of AccessControl declared to support ERC165 detection.\\n */\\ninterface IAccessControl {\\n /**\\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\\n *\\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\\n * {RoleAdminChanged} not being emitted signaling this.\\n *\\n * _Available since v3.1._\\n */\\n event RoleAdminChanged(\\n bytes32 indexed role,\\n bytes32 indexed previousAdminRole,\\n bytes32 indexed newAdminRole\\n );\\n\\n /**\\n * @dev Emitted when `account` is granted `role`.\\n *\\n * `sender` is the account that originated the contract call, an admin role\\n * bearer except when using {AccessControl-_setupRole}.\\n */\\n event RoleGranted(\\n bytes32 indexed role,\\n address indexed account,\\n address indexed sender\\n );\\n\\n /**\\n * @dev Emitted when `account` is revoked `role`.\\n *\\n * `sender` is the account that originated the contract call:\\n * - if using `revokeRole`, it is the admin role bearer\\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\\n */\\n event RoleRevoked(\\n bytes32 indexed role,\\n address indexed account,\\n address indexed sender\\n );\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account)\\n external\\n view\\n returns (bool);\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function grantRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n */\\n function revokeRole(bytes32 role, address account) external;\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been granted `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n */\\n function renounceRole(bytes32 role, address account) external;\\n}\\n\\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\\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\\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\\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 IERC165 {\\n /**\\n * @dev Returns true if this contract implements the interface defined by\\n * `interfaceId`. See the corresponding\\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\\n * to learn more about how these ids are created.\\n *\\n * This function call must use less than 30 000 gas.\\n */\\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\\n}\\n\\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Implementation of the {IERC165} interface.\\n *\\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\\n * for the additional interface id that will be supported. For example:\\n *\\n * ```solidity\\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\\n * }\\n * ```\\n *\\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\\n */\\nabstract contract ERC165 is IERC165 {\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return interfaceId == type(IERC165).interfaceId;\\n }\\n}\\n\\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\\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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = sqrt(a);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log2(value);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log10(value);\\n return\\n result +\\n (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)\\n internal\\n pure\\n returns (uint256)\\n {\\n unchecked {\\n uint256 result = log256(value);\\n return\\n result +\\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\\n\\npragma solidity ^0.8.0;\\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)\\n internal\\n pure\\n returns (string memory)\\n {\\n bytes memory buffer = new bytes(2 * length + 2);\\n buffer[0] = \\\"0\\\";\\n buffer[1] = \\\"x\\\";\\n for (uint256 i = 2 * length + 1; i > 1; --i) {\\n buffer[i] = _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\\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Contract module that allows children to implement role-based access\\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\\n * members except through off-chain means by accessing the contract event logs. Some\\n * applications may benefit from on-chain enumerability, for those cases see\\n * {AccessControlEnumerable}.\\n *\\n * Roles are referred to by their `bytes32` identifier. These should be exposed\\n * in the external API and be unique. The best way to achieve this is by\\n * using `public constant` hash digests:\\n *\\n * ```\\n * bytes32 public constant MY_ROLE = keccak256(\\\"MY_ROLE\\\");\\n * ```\\n *\\n * Roles can be used to represent a set of permissions. To restrict access to a\\n * function call, use {hasRole}:\\n *\\n * ```\\n * function foo() public {\\n * require(hasRole(MY_ROLE, msg.sender));\\n * ...\\n * }\\n * ```\\n *\\n * Roles can be granted and revoked dynamically via the {grantRole} and\\n * {revokeRole} functions. Each role has an associated admin role, and only\\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\\n *\\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\\n * that only accounts with this role will be able to grant or revoke other\\n * roles. More complex role relationships can be created by using\\n * {_setRoleAdmin}.\\n *\\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\\n * grant and revoke this role. Extra precautions should be taken to secure\\n * accounts that have been granted it.\\n */\\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\\n struct RoleData {\\n mapping(address => bool) members;\\n bytes32 adminRole;\\n }\\n\\n mapping(bytes32 => RoleData) private _roles;\\n\\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\\n\\n /**\\n * @dev Modifier that checks that an account has a specific role. Reverts\\n * with a standardized message including the required role.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n *\\n * _Available since v4.1._\\n */\\n modifier onlyRole(bytes32 role) {\\n _checkRole(role);\\n _;\\n }\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return\\n interfaceId == type(IAccessControl).interfaceId ||\\n super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns `true` if `account` has been granted `role`.\\n */\\n function hasRole(bytes32 role, address account)\\n public\\n view\\n virtual\\n override\\n returns (bool)\\n {\\n return _roles[role].members[account];\\n }\\n\\n /**\\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\\n * Overriding this function changes the behavior of the {onlyRole} modifier.\\n *\\n * Format of the revert message is described in {_checkRole}.\\n *\\n * _Available since v4.6._\\n */\\n function _checkRole(bytes32 role) internal view virtual {\\n _checkRole(role, _msgSender());\\n }\\n\\n /**\\n * @dev Revert with a standard message if `account` is missing `role`.\\n *\\n * The format of the revert reason is given by the following regular expression:\\n *\\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\\n */\\n function _checkRole(bytes32 role, address account) internal view virtual {\\n if (!hasRole(role, account)) {\\n revert(\\n string(\\n abi.encodePacked(\\n \\\"AccessControl: account \\\",\\n Strings.toHexString(account),\\n \\\" is missing role \\\",\\n Strings.toHexString(uint256(role), 32)\\n )\\n )\\n );\\n }\\n }\\n\\n /**\\n * @dev Returns the admin role that controls `role`. See {grantRole} and\\n * {revokeRole}.\\n *\\n * To change a role's admin, use {_setRoleAdmin}.\\n */\\n function getRoleAdmin(bytes32 role)\\n public\\n view\\n virtual\\n override\\n returns (bytes32)\\n {\\n return _roles[role].adminRole;\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function grantRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n onlyRole(getRoleAdmin(role))\\n {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have ``role``'s admin role.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function revokeRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n onlyRole(getRoleAdmin(role))\\n {\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Revokes `role` from the calling account.\\n *\\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\\n * purpose is to provide a mechanism for accounts to lose their privileges\\n * if they are compromised (such as when a trusted device is misplaced).\\n *\\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\\n * event.\\n *\\n * Requirements:\\n *\\n * - the caller must be `account`.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function renounceRole(bytes32 role, address account)\\n public\\n virtual\\n override\\n {\\n require(\\n account == _msgSender(),\\n \\\"AccessControl: can only renounce roles for self\\\"\\n );\\n\\n _revokeRole(role, account);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * If `account` had not been already granted `role`, emits a {RoleGranted}\\n * event. Note that unlike {grantRole}, this function doesn't perform any\\n * checks on the calling account.\\n *\\n * May emit a {RoleGranted} event.\\n *\\n * [WARNING]\\n * ====\\n * This function should only be called from the constructor when setting\\n * up the initial roles for the system.\\n *\\n * Using this function in any other way is effectively circumventing the admin\\n * system imposed by {AccessControl}.\\n * ====\\n *\\n * NOTE: This function is deprecated in favor of {_grantRole}.\\n */\\n function _setupRole(bytes32 role, address account) internal virtual {\\n _grantRole(role, account);\\n }\\n\\n /**\\n * @dev Sets `adminRole` as ``role``'s admin role.\\n *\\n * Emits a {RoleAdminChanged} event.\\n */\\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\\n bytes32 previousAdminRole = getRoleAdmin(role);\\n _roles[role].adminRole = adminRole;\\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\\n }\\n\\n /**\\n * @dev Grants `role` to `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleGranted} event.\\n */\\n function _grantRole(bytes32 role, address account) internal virtual {\\n if (!hasRole(role, account)) {\\n _roles[role].members[account] = true;\\n emit RoleGranted(role, account, _msgSender());\\n }\\n }\\n\\n /**\\n * @dev Revokes `role` from `account`.\\n *\\n * Internal function without access restriction.\\n *\\n * May emit a {RoleRevoked} event.\\n */\\n function _revokeRole(bytes32 role, address account) internal virtual {\\n if (hasRole(role, account)) {\\n _roles[role].members[account] = false;\\n emit RoleRevoked(role, account, _msgSender());\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev _Available since v3.1._\\n */\\ninterface IERC1155Receiver is IERC165 {\\n /**\\n * @dev Handles the receipt of a single ERC1155 token type. This function is\\n * called at the end of a `safeTransferFrom` after the balance has been updated.\\n *\\n * NOTE: To accept the transfer, this must return\\n * `bytes4(keccak256(\\\"onERC1155Received(address,address,uint256,uint256,bytes)\\\"))`\\n * (i.e. 0xf23a6e61, or its own function selector).\\n *\\n * @param operator The address which initiated the transfer (i.e. msg.sender)\\n * @param from The address which previously owned the token\\n * @param id The ID of the token being transferred\\n * @param value The amount of tokens being transferred\\n * @param data Additional data with no specified format\\n * @return `bytes4(keccak256(\\\"onERC1155Received(address,address,uint256,uint256,bytes)\\\"))` if transfer is allowed\\n */\\n function onERC1155Received(\\n address operator,\\n address from,\\n uint256 id,\\n uint256 value,\\n bytes calldata data\\n ) external returns (bytes4);\\n\\n /**\\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\\n * is called at the end of a `safeBatchTransferFrom` after the balances have\\n * been updated.\\n *\\n * NOTE: To accept the transfer(s), this must return\\n * `bytes4(keccak256(\\\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\\\"))`\\n * (i.e. 0xbc197c81, or its own function selector).\\n *\\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\\n * @param from The address which previously owned the token\\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\\n * @param data Additional data with no specified format\\n * @return `bytes4(keccak256(\\\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\\\"))` if transfer is allowed\\n */\\n function onERC1155BatchReceived(\\n address operator,\\n address from,\\n uint256[] calldata ids,\\n uint256[] calldata values,\\n bytes calldata data\\n ) external returns (bytes4);\\n}\\n\\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title ERC721 token receiver interface\\n * @dev Interface for any contract that wants to support safeTransfers\\n * from ERC721 asset contracts.\\n */\\ninterface IERC721Receiver {\\n /**\\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\\n * by `operator` from `from`, this function is called.\\n *\\n * It must return its Solidity selector to confirm the token transfer.\\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\\n *\\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\\n */\\n function onERC721Received(\\n address operator,\\n address from,\\n uint256 tokenId,\\n bytes calldata data\\n ) external returns (bytes4);\\n}\\n\\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\\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(\\n address(this).balance >= amount,\\n \\\"Address: insufficient balance\\\"\\n );\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(\\n success,\\n \\\"Address: unable to send value, recipient may have reverted\\\"\\n );\\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)\\n internal\\n returns (bytes memory)\\n {\\n return\\n functionCallWithValue(\\n target,\\n data,\\n 0,\\n \\\"Address: low-level call failed\\\"\\n );\\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\\n functionCallWithValue(\\n target,\\n data,\\n value,\\n \\\"Address: low-level call with value failed\\\"\\n );\\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(\\n address(this).balance >= value,\\n \\\"Address: insufficient balance for call\\\"\\n );\\n (bool success, bytes memory returndata) = target.call{value: value}(\\n data\\n );\\n return\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n internal\\n view\\n returns (bytes memory)\\n {\\n return\\n functionStaticCall(\\n target,\\n data,\\n \\\"Address: low-level static call failed\\\"\\n );\\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\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n internal\\n returns (bytes memory)\\n {\\n return\\n functionDelegateCall(\\n target,\\n data,\\n \\\"Address: low-level delegate call failed\\\"\\n );\\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\\n verifyCallResultFromTarget(\\n target,\\n success,\\n returndata,\\n errorMessage\\n );\\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)\\n private\\n pure\\n {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Contract module which acts as a timelocked controller. When set as the\\n * owner of an `Ownable` smart contract, it enforces a timelock on all\\n * `onlyOwner` maintenance operations. This gives time for users of the\\n * controlled contract to exit before a potentially dangerous maintenance\\n * operation is applied.\\n *\\n * By default, this contract is self administered, meaning administration tasks\\n * have to go through the timelock process. The proposer (resp executor) role\\n * is in charge of proposing (resp executing) operations. A common use case is\\n * to position this {TimelockController} as the owner of a smart contract, with\\n * a multisig or a DAO as the sole proposer.\\n *\\n * _Available since v3.3._\\n */\\ncontract TimelockController is\\n AccessControl,\\n IERC721Receiver,\\n IERC1155Receiver\\n{\\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\\n keccak256(\\\"TIMELOCK_ADMIN_ROLE\\\");\\n bytes32 public constant PROPOSER_ROLE = keccak256(\\\"PROPOSER_ROLE\\\");\\n bytes32 public constant EXECUTOR_ROLE = keccak256(\\\"EXECUTOR_ROLE\\\");\\n bytes32 public constant CANCELLER_ROLE = keccak256(\\\"CANCELLER_ROLE\\\");\\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\\n\\n mapping(bytes32 => uint256) private _timestamps;\\n uint256 private _minDelay;\\n\\n /**\\n * @dev Emitted when a call is scheduled as part of operation `id`.\\n */\\n event CallScheduled(\\n bytes32 indexed id,\\n uint256 indexed index,\\n address target,\\n uint256 value,\\n bytes data,\\n bytes32 predecessor,\\n uint256 delay\\n );\\n\\n /**\\n * @dev Emitted when a call is performed as part of operation `id`.\\n */\\n event CallExecuted(\\n bytes32 indexed id,\\n uint256 indexed index,\\n address target,\\n uint256 value,\\n bytes data\\n );\\n\\n /**\\n * @dev Emitted when operation `id` is cancelled.\\n */\\n event Cancelled(bytes32 indexed id);\\n\\n /**\\n * @dev Emitted when the minimum delay for future operations is modified.\\n */\\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\\n\\n /**\\n * @dev Initializes the contract with the following parameters:\\n *\\n * - `minDelay`: initial minimum delay for operations\\n * - `proposers`: accounts to be granted proposer and canceller roles\\n * - `executors`: accounts to be granted executor role\\n * - `admin`: optional account to be granted admin role; disable with zero address\\n *\\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\\n * without being subject to delay, but this role should be subsequently renounced in favor of\\n * administration through timelocked proposals. Previous versions of this contract would assign\\n * this admin to the deployer automatically and should be renounced as well.\\n */\\n constructor(\\n uint256 minDelay,\\n address[] memory proposers,\\n address[] memory executors,\\n address admin\\n ) {\\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\\n\\n // self administration\\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\\n\\n // optional admin\\n if (admin != address(0)) {\\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\\n }\\n\\n // register proposers and cancellers\\n for (uint256 i = 0; i < proposers.length; ++i) {\\n _setupRole(PROPOSER_ROLE, proposers[i]);\\n _setupRole(CANCELLER_ROLE, proposers[i]);\\n }\\n\\n // register executors\\n for (uint256 i = 0; i < executors.length; ++i) {\\n _setupRole(EXECUTOR_ROLE, executors[i]);\\n }\\n\\n _minDelay = minDelay;\\n emit MinDelayChange(0, minDelay);\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only by a certain role. In\\n * addition to checking the sender's role, `address(0)` 's role is also\\n * considered. Granting a role to `address(0)` is equivalent to enabling\\n * this role for everyone.\\n */\\n modifier onlyRoleOrOpenRole(bytes32 role) {\\n if (!hasRole(role, address(0))) {\\n _checkRole(role, _msgSender());\\n }\\n _;\\n }\\n\\n /**\\n * @dev Contract might receive/hold ETH as part of the maintenance process.\\n */\\n receive() external payable {}\\n\\n /**\\n * @dev See {IERC165-supportsInterface}.\\n */\\n function supportsInterface(bytes4 interfaceId)\\n public\\n view\\n virtual\\n override(IERC165, AccessControl)\\n returns (bool)\\n {\\n return\\n interfaceId == type(IERC1155Receiver).interfaceId ||\\n super.supportsInterface(interfaceId);\\n }\\n\\n /**\\n * @dev Returns whether an id correspond to a registered operation. This\\n * includes both Pending, Ready and Done operations.\\n */\\n function isOperation(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool registered)\\n {\\n return getTimestamp(id) > 0;\\n }\\n\\n /**\\n * @dev Returns whether an operation is pending or not.\\n */\\n function isOperationPending(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool pending)\\n {\\n return getTimestamp(id) > _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Returns whether an operation is ready or not.\\n */\\n function isOperationReady(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool ready)\\n {\\n uint256 timestamp = getTimestamp(id);\\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\\n }\\n\\n /**\\n * @dev Returns whether an operation is done or not.\\n */\\n function isOperationDone(bytes32 id)\\n public\\n view\\n virtual\\n returns (bool done)\\n {\\n return getTimestamp(id) == _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Returns the timestamp at with an operation becomes ready (0 for\\n * unset operations, 1 for done operations).\\n */\\n function getTimestamp(bytes32 id)\\n public\\n view\\n virtual\\n returns (uint256 timestamp)\\n {\\n return _timestamps[id];\\n }\\n\\n /**\\n * @dev Returns the minimum delay for an operation to become valid.\\n *\\n * This value can be changed by executing an operation that calls `updateDelay`.\\n */\\n function getMinDelay() public view virtual returns (uint256 duration) {\\n return _minDelay;\\n }\\n\\n /**\\n * @dev Returns the identifier of an operation containing a single\\n * transaction.\\n */\\n function hashOperation(\\n address target,\\n uint256 value,\\n bytes calldata data,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public pure virtual returns (bytes32 hash) {\\n return keccak256(abi.encode(target, value, data, predecessor, salt));\\n }\\n\\n /**\\n * @dev Returns the identifier of an operation containing a batch of\\n * transactions.\\n */\\n function hashOperationBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public pure virtual returns (bytes32 hash) {\\n return\\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\\n }\\n\\n /**\\n * @dev Schedule an operation containing a single transaction.\\n *\\n * Emits a {CallScheduled} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'proposer' role.\\n */\\n function schedule(\\n address target,\\n uint256 value,\\n bytes calldata data,\\n bytes32 predecessor,\\n bytes32 salt,\\n uint256 delay\\n ) public virtual onlyRole(PROPOSER_ROLE) {\\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\\n _schedule(id, delay);\\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\\n }\\n\\n /**\\n * @dev Schedule an operation containing a batch of transactions.\\n *\\n * Emits one {CallScheduled} event per transaction in the batch.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'proposer' role.\\n */\\n function scheduleBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt,\\n uint256 delay\\n ) public virtual onlyRole(PROPOSER_ROLE) {\\n require(\\n targets.length == values.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n require(\\n targets.length == payloads.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n\\n bytes32 id = hashOperationBatch(\\n targets,\\n values,\\n payloads,\\n predecessor,\\n salt\\n );\\n _schedule(id, delay);\\n for (uint256 i = 0; i < targets.length; ++i) {\\n emit CallScheduled(\\n id,\\n i,\\n targets[i],\\n values[i],\\n payloads[i],\\n predecessor,\\n delay\\n );\\n }\\n }\\n\\n /**\\n * @dev Schedule an operation that is to becomes valid after a given delay.\\n */\\n function _schedule(bytes32 id, uint256 delay) private {\\n require(\\n !isOperation(id),\\n \\\"TimelockController: operation already scheduled\\\"\\n );\\n require(\\n delay >= getMinDelay(),\\n \\\"TimelockController: insufficient delay\\\"\\n );\\n _timestamps[id] = block.timestamp + delay;\\n }\\n\\n /**\\n * @dev Cancel an operation.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'canceller' role.\\n */\\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\\n require(\\n isOperationPending(id),\\n \\\"TimelockController: operation cannot be cancelled\\\"\\n );\\n delete _timestamps[id];\\n\\n emit Cancelled(id);\\n }\\n\\n /**\\n * @dev Execute an (ready) operation containing a single transaction.\\n *\\n * Emits a {CallExecuted} event.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'executor' role.\\n */\\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\\n // thus any modifications to the operation during reentrancy should be caught.\\n // slither-disable-next-line reentrancy-eth\\n function execute(\\n address target,\\n uint256 value,\\n bytes calldata payload,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\\n\\n _beforeCall(id, predecessor);\\n _execute(target, value, payload);\\n emit CallExecuted(id, 0, target, value, payload);\\n _afterCall(id);\\n }\\n\\n /**\\n * @dev Execute an (ready) operation containing a batch of transactions.\\n *\\n * Emits one {CallExecuted} event per transaction in the batch.\\n *\\n * Requirements:\\n *\\n * - the caller must have the 'executor' role.\\n */\\n function executeBatch(\\n address[] calldata targets,\\n uint256[] calldata values,\\n bytes[] calldata payloads,\\n bytes32 predecessor,\\n bytes32 salt\\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\\n require(\\n targets.length == values.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n require(\\n targets.length == payloads.length,\\n \\\"TimelockController: length mismatch\\\"\\n );\\n\\n bytes32 id = hashOperationBatch(\\n targets,\\n values,\\n payloads,\\n predecessor,\\n salt\\n );\\n\\n _beforeCall(id, predecessor);\\n for (uint256 i = 0; i < targets.length; ++i) {\\n address target = targets[i];\\n uint256 value = values[i];\\n bytes calldata payload = payloads[i];\\n _execute(target, value, payload);\\n emit CallExecuted(id, i, target, value, payload);\\n }\\n _afterCall(id);\\n }\\n\\n /**\\n * @dev Execute an operation's call.\\n */\\n function _execute(\\n address target,\\n uint256 value,\\n bytes calldata data\\n ) internal virtual {\\n (bool success, ) = target.call{value: value}(data);\\n require(success, \\\"TimelockController: underlying transaction reverted\\\");\\n }\\n\\n /**\\n * @dev Checks before execution of an operation's calls.\\n */\\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\\n require(\\n isOperationReady(id),\\n \\\"TimelockController: operation is not ready\\\"\\n );\\n require(\\n predecessor == bytes32(0) || isOperationDone(predecessor),\\n \\\"TimelockController: missing dependency\\\"\\n );\\n }\\n\\n /**\\n * @dev Checks after execution of an operation's calls.\\n */\\n function _afterCall(bytes32 id) private {\\n require(\\n isOperationReady(id),\\n \\\"TimelockController: operation is not ready\\\"\\n );\\n _timestamps[id] = _DONE_TIMESTAMP;\\n }\\n\\n /**\\n * @dev Changes the minimum timelock duration for future operations.\\n *\\n * Emits a {MinDelayChange} event.\\n *\\n * Requirements:\\n *\\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\\n */\\n function updateDelay(uint256 newDelay) external virtual {\\n require(\\n msg.sender == address(this),\\n \\\"TimelockController: caller must be timelock\\\"\\n );\\n emit MinDelayChange(_minDelay, newDelay);\\n _minDelay = newDelay;\\n }\\n\\n /**\\n * @dev See {IERC721Receiver-onERC721Received}.\\n */\\n function onERC721Received(\\n address,\\n address,\\n uint256,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC721Received.selector;\\n }\\n\\n /**\\n * @dev See {IERC1155Receiver-onERC1155Received}.\\n */\\n function onERC1155Received(\\n address,\\n address,\\n uint256,\\n uint256,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC1155Received.selector;\\n }\\n\\n /**\\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\\n */\\n function onERC1155BatchReceived(\\n address,\\n address,\\n uint256[] memory,\\n uint256[] memory,\\n bytes memory\\n ) public virtual override returns (bytes4) {\\n return this.onERC1155BatchReceived.selector;\\n }\\n}\",\"keccak256\":\"0xc3448009aeaaa7eebccd9cd969e69cb788dcbce5aa936021862c0b59197d426a\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x60806040523480156200001157600080fd5b506040516200232638038062002326833981016040819052620000349162000408565b6200004f600080516020620022a6833981519152806200022d565b62000079600080516020620022c6833981519152600080516020620022a68339815191526200022d565b620000a3600080516020620022e6833981519152600080516020620022a68339815191526200022d565b620000cd60008051602062002306833981519152600080516020620022a68339815191526200022d565b620000e8600080516020620022a68339815191523062000278565b6001600160a01b03811615620001135762000113600080516020620022a68339815191528262000278565b60005b835181101562000199576200015d600080516020620022c68339815191528583815181106200014957620001496200048f565b60200260200101516200027860201b60201c565b62000186600080516020620023068339815191528583815181106200014957620001496200048f565b6200019181620004a5565b905062000116565b5060005b8251811015620001e357620001d0600080516020620022e68339815191528483815181106200014957620001496200048f565b620001db81620004a5565b90506200019d565b5060028490556040805160008152602081018690527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a150505050620004cf565b600082815260208190526040808220600101805490849055905190918391839186917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9190a4505050565b62000284828262000288565b5050565b6000828152602081815260408083206001600160a01b038516845290915290205460ff1662000284576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055620002e43390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b634e487b7160e01b600052604160045260246000fd5b80516001600160a01b03811681146200035657600080fd5b919050565b600082601f8301126200036d57600080fd5b815160206001600160401b03808311156200038c576200038c62000328565b8260051b604051601f19603f83011681018181108482111715620003b457620003b462000328565b604052938452858101830193838101925087851115620003d357600080fd5b83870191505b84821015620003fd57620003ed826200033e565b83529183019190830190620003d9565b979650505050505050565b600080600080608085870312156200041f57600080fd5b845160208601519094506001600160401b03808211156200043f57600080fd5b6200044d888389016200035b565b945060408701519150808211156200046457600080fd5b5062000473878288016200035b565b92505062000484606086016200033e565b905092959194509250565b634e487b7160e01b600052603260045260246000fd5b6000600019821415620004c857634e487b7160e01b600052601160045260246000fd5b5060010190565b611dc780620004df6000396000f3fe6080604052600436106101bb5760003560e01c80638065657f116100ec578063bc197c811161008a578063d547741f11610064578063d547741f14610582578063e38335e5146105a2578063f23a6e61146105b5578063f27a0c92146105e157600080fd5b8063bc197c8114610509578063c4d252f514610535578063d45c44351461055557600080fd5b806391d14854116100c657806391d1485414610480578063a217fddf146104a0578063b08e51c0146104b5578063b1c5f427146104e957600080fd5b80638065657f1461040c5780638f2a0bb01461042c5780638f61f4f51461044c57600080fd5b8063248a9ca31161015957806331d507501161013357806331d507501461038c57806336568abe146103ac578063584b153e146103cc57806364d62353146103ec57600080fd5b8063248a9ca31461030b5780632ab0f5291461033b5780632f2ff15d1461036c57600080fd5b80630d3cf6fc116101955780630d3cf6fc14610260578063134008d31461029457806313bc9f20146102a7578063150b7a02146102c757600080fd5b806301d5062a146101c757806301ffc9a7146101e957806307bd02651461021e57600080fd5b366101c257005b600080fd5b3480156101d357600080fd5b506101e76101e23660046113c0565b6105f6565b005b3480156101f557600080fd5b50610209610204366004611434565b61068b565b60405190151581526020015b60405180910390f35b34801561022a57600080fd5b506102527fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610215565b34801561026c57600080fd5b506102527f5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca581565b6101e76102a236600461145e565b6106b6565b3480156102b357600080fd5b506102096102c23660046114c9565b61076b565b3480156102d357600080fd5b506102f26102e2366004611597565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610215565b34801561031757600080fd5b506102526103263660046114c9565b60009081526020819052604090206001015490565b34801561034757600080fd5b506102096103563660046114c9565b6000908152600160208190526040909120541490565b34801561037857600080fd5b506101e76103873660046115fe565b610791565b34801561039857600080fd5b506102096103a73660046114c9565b6107bb565b3480156103b857600080fd5b506101e76103c73660046115fe565b6107d4565b3480156103d857600080fd5b506102096103e73660046114c9565b610857565b3480156103f857600080fd5b506101e76104073660046114c9565b61086d565b34801561041857600080fd5b5061025261042736600461145e565b610911565b34801561043857600080fd5b506101e761044736600461166e565b610950565b34801561045857600080fd5b506102527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b34801561048c57600080fd5b5061020961049b3660046115fe565b610aa2565b3480156104ac57600080fd5b50610252600081565b3480156104c157600080fd5b506102527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156104f557600080fd5b5061025261050436600461171f565b610acb565b34801561051557600080fd5b506102f2610524366004611846565b63bc197c8160e01b95945050505050565b34801561054157600080fd5b506101e76105503660046114c9565b610b10565b34801561056157600080fd5b506102526105703660046114c9565b60009081526001602052604090205490565b34801561058e57600080fd5b506101e761059d3660046115fe565b610be5565b6101e76105b036600461171f565b610c0a565b3480156105c157600080fd5b506102f26105d03660046118ef565b63f23a6e6160e01b95945050505050565b3480156105ed57600080fd5b50600254610252565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161062081610d94565b6000610630898989898989610911565b905061063c8184610da1565b6000817f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8b8b8b8b8b8a6040516106789695949392919061197c565b60405180910390a3505050505050505050565b60006001600160e01b03198216630271189760e51b14806106b057506106b082610e90565b92915050565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e636106e2816000610aa2565b6106f0576106f08133610ec5565b6000610700888888888888610911565b905061070c8185610f1e565b61071888888888610fba565b6000817fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b588a8a8a8a60405161075094939291906119b9565b60405180910390a36107618161108d565b5050505050505050565b60008181526001602052604081205460018111801561078a5750428111155b9392505050565b6000828152602081905260409020600101546107ac81610d94565b6107b683836110c6565b505050565b60008181526001602052604081205481905b1192915050565b6001600160a01b03811633146108495760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b610853828261114a565b5050565b60008181526001602081905260408220546107cd565b3330146108d05760405162461bcd60e51b815260206004820152602b60248201527f54696d656c6f636b436f6e74726f6c6c65723a2063616c6c6572206d7573742060448201526a62652074696d656c6f636b60a81b6064820152608401610840565b60025460408051918252602082018390527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a1600255565b600086868686868660405160200161092e9695949392919061197c565b6040516020818303038152906040528051906020012090509695505050505050565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161097a81610d94565b8887146109995760405162461bcd60e51b8152600401610840906119eb565b8885146109b85760405162461bcd60e51b8152600401610840906119eb565b60006109ca8b8b8b8b8b8b8b8b610acb565b90506109d68184610da1565b60005b8a811015610a945780827f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8e8e85818110610a1657610a16611a2e565b9050602002016020810190610a2b9190611a44565b8d8d86818110610a3d57610a3d611a2e565b905060200201358c8c87818110610a5657610a56611a2e565b9050602002810190610a689190611a5f565b8c8b604051610a7c9695949392919061197c565b60405180910390a3610a8d81611abb565b90506109d9565b505050505050505050505050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60008888888888888888604051602001610aec989796959493929190611b66565b60405160208183030381529060405280519060200120905098975050505050505050565b7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783610b3a81610d94565b610b4382610857565b610ba95760405162461bcd60e51b815260206004820152603160248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e2063616044820152701b9b9bdd0818994818d85b98d95b1b1959607a1b6064820152608401610840565b6000828152600160205260408082208290555183917fbaa1eb22f2a492ba1a5fea61b8df4d27c6c8b5f3971e63bb58fa14ff72eedb7091a25050565b600082815260208190526040902060010154610c0081610d94565b6107b6838361114a565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63610c36816000610aa2565b610c4457610c448133610ec5565b878614610c635760405162461bcd60e51b8152600401610840906119eb565b878414610c825760405162461bcd60e51b8152600401610840906119eb565b6000610c948a8a8a8a8a8a8a8a610acb565b9050610ca08185610f1e565b60005b89811015610d7e5760008b8b83818110610cbf57610cbf611a2e565b9050602002016020810190610cd49190611a44565b905060008a8a84818110610cea57610cea611a2e565b9050602002013590503660008a8a86818110610d0857610d08611a2e565b9050602002810190610d1a9190611a5f565b91509150610d2a84848484610fba565b84867fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b5886868686604051610d6194939291906119b9565b60405180910390a35050505080610d7790611abb565b9050610ca3565b50610d888161108d565b50505050505050505050565b610d9e8133610ec5565b50565b610daa826107bb565b15610e0f5760405162461bcd60e51b815260206004820152602f60248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e20616c60448201526e1c9958591e481cd8da19591d5b1959608a1b6064820152608401610840565b600254811015610e705760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a20696e73756666696369656e746044820152652064656c617960d01b6064820152608401610840565b610e7a8142611c11565b6000928352600160205260409092209190915550565b60006001600160e01b03198216637965db0b60e01b14806106b057506301ffc9a760e01b6001600160e01b03198316146106b0565b610ecf8282610aa2565b61085357610edc816111af565b610ee78360206111c1565b604051602001610ef8929190611c59565b60408051601f198184030181529082905262461bcd60e51b825261084091600401611cce565b610f278261076b565b610f435760405162461bcd60e51b815260040161084090611d01565b801580610f5f5750600081815260016020819052604090912054145b6108535760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a206d697373696e6720646570656044820152656e64656e637960d01b6064820152608401610840565b6000846001600160a01b0316848484604051610fd7929190611d4b565b60006040518083038185875af1925050503d8060008114611014576040519150601f19603f3d011682016040523d82523d6000602084013e611019565b606091505b50509050806110865760405162461bcd60e51b815260206004820152603360248201527f54696d656c6f636b436f6e74726f6c6c65723a20756e6465726c79696e6720746044820152721c985b9cd858dd1a5bdb881c995d995c9d1959606a1b6064820152608401610840565b5050505050565b6110968161076b565b6110b25760405162461bcd60e51b815260040161084090611d01565b600090815260016020819052604090912055565b6110d08282610aa2565b610853576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556111063390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6111548282610aa2565b15610853576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60606106b06001600160a01b03831660145b606060006111d0836002611d5b565b6111db906002611c11565b6001600160401b038111156111f2576111f26114e2565b6040519080825280601f01601f19166020018201604052801561121c576020820181803683370190505b509050600360fc1b8160008151811061123757611237611a2e565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061126657611266611a2e565b60200101906001600160f81b031916908160001a905350600061128a846002611d5b565b611295906001611c11565b90505b600181111561130d576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106112c9576112c9611a2e565b1a60f81b8282815181106112df576112df611a2e565b60200101906001600160f81b031916908160001a90535060049490941c9361130681611d7a565b9050611298565b50831561078a5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610840565b80356001600160a01b038116811461137357600080fd5b919050565b60008083601f84011261138a57600080fd5b5081356001600160401b038111156113a157600080fd5b6020830191508360208285010111156113b957600080fd5b9250929050565b600080600080600080600060c0888a0312156113db57600080fd5b6113e48861135c565b96506020880135955060408801356001600160401b0381111561140657600080fd5b6114128a828b01611378565b989b979a50986060810135976080820135975060a09091013595509350505050565b60006020828403121561144657600080fd5b81356001600160e01b03198116811461078a57600080fd5b60008060008060008060a0878903121561147757600080fd5b6114808761135c565b95506020870135945060408701356001600160401b038111156114a257600080fd5b6114ae89828a01611378565b979a9699509760608101359660809091013595509350505050565b6000602082840312156114db57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715611520576115206114e2565b604052919050565b600082601f83011261153957600080fd5b81356001600160401b03811115611552576115526114e2565b611565601f8201601f19166020016114f8565b81815284602083860101111561157a57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156115ad57600080fd5b6115b68561135c565b93506115c46020860161135c565b92506040850135915060608501356001600160401b038111156115e657600080fd5b6115f287828801611528565b91505092959194509250565b6000806040838503121561161157600080fd5b823591506116216020840161135c565b90509250929050565b60008083601f84011261163c57600080fd5b5081356001600160401b0381111561165357600080fd5b6020830191508360208260051b85010111156113b957600080fd5b600080600080600080600080600060c08a8c03121561168c57600080fd5b89356001600160401b03808211156116a357600080fd5b6116af8d838e0161162a565b909b50995060208c01359150808211156116c857600080fd5b6116d48d838e0161162a565b909950975060408c01359150808211156116ed57600080fd5b506116fa8c828d0161162a565b9a9d999c50979a969997986060880135976080810135975060a0013595509350505050565b60008060008060008060008060a0898b03121561173b57600080fd5b88356001600160401b038082111561175257600080fd5b61175e8c838d0161162a565b909a50985060208b013591508082111561177757600080fd5b6117838c838d0161162a565b909850965060408b013591508082111561179c57600080fd5b506117a98b828c0161162a565b999c989b509699959896976060870135966080013595509350505050565b600082601f8301126117d857600080fd5b813560206001600160401b038211156117f3576117f36114e2565b8160051b6118028282016114f8565b928352848101820192828101908785111561181c57600080fd5b83870192505b8483101561183b57823582529183019190830190611822565b979650505050505050565b600080600080600060a0868803121561185e57600080fd5b6118678661135c565b94506118756020870161135c565b935060408601356001600160401b038082111561189157600080fd5b61189d89838a016117c7565b945060608801359150808211156118b357600080fd5b6118bf89838a016117c7565b935060808801359150808211156118d557600080fd5b506118e288828901611528565b9150509295509295909350565b600080600080600060a0868803121561190757600080fd5b6119108661135c565b945061191e6020870161135c565b9350604086013592506060860135915060808601356001600160401b0381111561194757600080fd5b6118e288828901611528565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60018060a01b038716815285602082015260a0604082015260006119a460a083018688611953565b60608301949094525060800152949350505050565b60018060a01b03851681528360208201526060604082015260006119e1606083018486611953565b9695505050505050565b60208082526023908201527f54696d656c6f636b436f6e74726f6c6c65723a206c656e677468206d69736d616040820152620e8c6d60eb1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215611a5657600080fd5b61078a8261135c565b6000808335601e19843603018112611a7657600080fd5b8301803591506001600160401b03821115611a9057600080fd5b6020019150368190038213156113b957600080fd5b634e487b7160e01b600052601160045260246000fd5b6000600019821415611acf57611acf611aa5565b5060010190565b81835260006020808501808196508560051b810191508460005b87811015611b595782840389528135601e19883603018112611b1157600080fd5b870180356001600160401b03811115611b2957600080fd5b803603891315611b3857600080fd5b611b458682898501611953565b9a87019a9550505090840190600101611af0565b5091979650505050505050565b60a0808252810188905260008960c08301825b8b811015611ba7576001600160a01b03611b928461135c565b16825260209283019290910190600101611b79565b5083810360208501528881526001600160fb1b03891115611bc757600080fd5b8860051b9150818a602083013781810191505060208101600081526020848303016040850152611bf881888a611ad6565b6060850196909652505050608001529695505050505050565b60008219821115611c2457611c24611aa5565b500190565b60005b83811015611c44578181015183820152602001611c2c565b83811115611c53576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c91816017850160208801611c29565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611cc2816028840160208801611c29565b01602801949350505050565b6020815260008251806020840152611ced816040850160208701611c29565b601f01601f19169190910160400192915050565b6020808252602a908201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e206973604082015269206e6f7420726561647960b01b606082015260800190565b8183823760009101908152919050565b6000816000190483118215151615611d7557611d75611aa5565b500290565b600081611d8957611d89611aa5565b50600019019056fea2646970667358221220dca2012434ae0ee932ca779f9ca2670c90f60d6e9240e5d6e19d5d2d78265ff464736f6c634300080b00335f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5b09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1d8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63fd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783", + "deployedBytecode": "0x6080604052600436106101bb5760003560e01c80638065657f116100ec578063bc197c811161008a578063d547741f11610064578063d547741f14610582578063e38335e5146105a2578063f23a6e61146105b5578063f27a0c92146105e157600080fd5b8063bc197c8114610509578063c4d252f514610535578063d45c44351461055557600080fd5b806391d14854116100c657806391d1485414610480578063a217fddf146104a0578063b08e51c0146104b5578063b1c5f427146104e957600080fd5b80638065657f1461040c5780638f2a0bb01461042c5780638f61f4f51461044c57600080fd5b8063248a9ca31161015957806331d507501161013357806331d507501461038c57806336568abe146103ac578063584b153e146103cc57806364d62353146103ec57600080fd5b8063248a9ca31461030b5780632ab0f5291461033b5780632f2ff15d1461036c57600080fd5b80630d3cf6fc116101955780630d3cf6fc14610260578063134008d31461029457806313bc9f20146102a7578063150b7a02146102c757600080fd5b806301d5062a146101c757806301ffc9a7146101e957806307bd02651461021e57600080fd5b366101c257005b600080fd5b3480156101d357600080fd5b506101e76101e23660046113c0565b6105f6565b005b3480156101f557600080fd5b50610209610204366004611434565b61068b565b60405190151581526020015b60405180910390f35b34801561022a57600080fd5b506102527fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610215565b34801561026c57600080fd5b506102527f5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca581565b6101e76102a236600461145e565b6106b6565b3480156102b357600080fd5b506102096102c23660046114c9565b61076b565b3480156102d357600080fd5b506102f26102e2366004611597565b630a85bd0160e11b949350505050565b6040516001600160e01b03199091168152602001610215565b34801561031757600080fd5b506102526103263660046114c9565b60009081526020819052604090206001015490565b34801561034757600080fd5b506102096103563660046114c9565b6000908152600160208190526040909120541490565b34801561037857600080fd5b506101e76103873660046115fe565b610791565b34801561039857600080fd5b506102096103a73660046114c9565b6107bb565b3480156103b857600080fd5b506101e76103c73660046115fe565b6107d4565b3480156103d857600080fd5b506102096103e73660046114c9565b610857565b3480156103f857600080fd5b506101e76104073660046114c9565b61086d565b34801561041857600080fd5b5061025261042736600461145e565b610911565b34801561043857600080fd5b506101e761044736600461166e565b610950565b34801561045857600080fd5b506102527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b34801561048c57600080fd5b5061020961049b3660046115fe565b610aa2565b3480156104ac57600080fd5b50610252600081565b3480156104c157600080fd5b506102527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156104f557600080fd5b5061025261050436600461171f565b610acb565b34801561051557600080fd5b506102f2610524366004611846565b63bc197c8160e01b95945050505050565b34801561054157600080fd5b506101e76105503660046114c9565b610b10565b34801561056157600080fd5b506102526105703660046114c9565b60009081526001602052604090205490565b34801561058e57600080fd5b506101e761059d3660046115fe565b610be5565b6101e76105b036600461171f565b610c0a565b3480156105c157600080fd5b506102f26105d03660046118ef565b63f23a6e6160e01b95945050505050565b3480156105ed57600080fd5b50600254610252565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161062081610d94565b6000610630898989898989610911565b905061063c8184610da1565b6000817f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8b8b8b8b8b8a6040516106789695949392919061197c565b60405180910390a3505050505050505050565b60006001600160e01b03198216630271189760e51b14806106b057506106b082610e90565b92915050565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e636106e2816000610aa2565b6106f0576106f08133610ec5565b6000610700888888888888610911565b905061070c8185610f1e565b61071888888888610fba565b6000817fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b588a8a8a8a60405161075094939291906119b9565b60405180910390a36107618161108d565b5050505050505050565b60008181526001602052604081205460018111801561078a5750428111155b9392505050565b6000828152602081905260409020600101546107ac81610d94565b6107b683836110c6565b505050565b60008181526001602052604081205481905b1192915050565b6001600160a01b03811633146108495760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b610853828261114a565b5050565b60008181526001602081905260408220546107cd565b3330146108d05760405162461bcd60e51b815260206004820152602b60248201527f54696d656c6f636b436f6e74726f6c6c65723a2063616c6c6572206d7573742060448201526a62652074696d656c6f636b60a81b6064820152608401610840565b60025460408051918252602082018390527f11c24f4ead16507c69ac467fbd5e4eed5fb5c699626d2cc6d66421df253886d5910160405180910390a1600255565b600086868686868660405160200161092e9695949392919061197c565b6040516020818303038152906040528051906020012090509695505050505050565b7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc161097a81610d94565b8887146109995760405162461bcd60e51b8152600401610840906119eb565b8885146109b85760405162461bcd60e51b8152600401610840906119eb565b60006109ca8b8b8b8b8b8b8b8b610acb565b90506109d68184610da1565b60005b8a811015610a945780827f4cf4410cc57040e44862ef0f45f3dd5a5e02db8eb8add648d4b0e236f1d07dca8e8e85818110610a1657610a16611a2e565b9050602002016020810190610a2b9190611a44565b8d8d86818110610a3d57610a3d611a2e565b905060200201358c8c87818110610a5657610a56611a2e565b9050602002810190610a689190611a5f565b8c8b604051610a7c9695949392919061197c565b60405180910390a3610a8d81611abb565b90506109d9565b505050505050505050505050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b60008888888888888888604051602001610aec989796959493929190611b66565b60405160208183030381529060405280519060200120905098975050505050505050565b7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783610b3a81610d94565b610b4382610857565b610ba95760405162461bcd60e51b815260206004820152603160248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e2063616044820152701b9b9bdd0818994818d85b98d95b1b1959607a1b6064820152608401610840565b6000828152600160205260408082208290555183917fbaa1eb22f2a492ba1a5fea61b8df4d27c6c8b5f3971e63bb58fa14ff72eedb7091a25050565b600082815260208190526040902060010154610c0081610d94565b6107b6838361114a565b7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63610c36816000610aa2565b610c4457610c448133610ec5565b878614610c635760405162461bcd60e51b8152600401610840906119eb565b878414610c825760405162461bcd60e51b8152600401610840906119eb565b6000610c948a8a8a8a8a8a8a8a610acb565b9050610ca08185610f1e565b60005b89811015610d7e5760008b8b83818110610cbf57610cbf611a2e565b9050602002016020810190610cd49190611a44565b905060008a8a84818110610cea57610cea611a2e565b9050602002013590503660008a8a86818110610d0857610d08611a2e565b9050602002810190610d1a9190611a5f565b91509150610d2a84848484610fba565b84867fc2617efa69bab66782fa219543714338489c4e9e178271560a91b82c3f612b5886868686604051610d6194939291906119b9565b60405180910390a35050505080610d7790611abb565b9050610ca3565b50610d888161108d565b50505050505050505050565b610d9e8133610ec5565b50565b610daa826107bb565b15610e0f5760405162461bcd60e51b815260206004820152602f60248201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e20616c60448201526e1c9958591e481cd8da19591d5b1959608a1b6064820152608401610840565b600254811015610e705760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a20696e73756666696369656e746044820152652064656c617960d01b6064820152608401610840565b610e7a8142611c11565b6000928352600160205260409092209190915550565b60006001600160e01b03198216637965db0b60e01b14806106b057506301ffc9a760e01b6001600160e01b03198316146106b0565b610ecf8282610aa2565b61085357610edc816111af565b610ee78360206111c1565b604051602001610ef8929190611c59565b60408051601f198184030181529082905262461bcd60e51b825261084091600401611cce565b610f278261076b565b610f435760405162461bcd60e51b815260040161084090611d01565b801580610f5f5750600081815260016020819052604090912054145b6108535760405162461bcd60e51b815260206004820152602660248201527f54696d656c6f636b436f6e74726f6c6c65723a206d697373696e6720646570656044820152656e64656e637960d01b6064820152608401610840565b6000846001600160a01b0316848484604051610fd7929190611d4b565b60006040518083038185875af1925050503d8060008114611014576040519150601f19603f3d011682016040523d82523d6000602084013e611019565b606091505b50509050806110865760405162461bcd60e51b815260206004820152603360248201527f54696d656c6f636b436f6e74726f6c6c65723a20756e6465726c79696e6720746044820152721c985b9cd858dd1a5bdb881c995d995c9d1959606a1b6064820152608401610840565b5050505050565b6110968161076b565b6110b25760405162461bcd60e51b815260040161084090611d01565b600090815260016020819052604090912055565b6110d08282610aa2565b610853576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556111063390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6111548282610aa2565b15610853576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60606106b06001600160a01b03831660145b606060006111d0836002611d5b565b6111db906002611c11565b6001600160401b038111156111f2576111f26114e2565b6040519080825280601f01601f19166020018201604052801561121c576020820181803683370190505b509050600360fc1b8160008151811061123757611237611a2e565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061126657611266611a2e565b60200101906001600160f81b031916908160001a905350600061128a846002611d5b565b611295906001611c11565b90505b600181111561130d576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106112c9576112c9611a2e565b1a60f81b8282815181106112df576112df611a2e565b60200101906001600160f81b031916908160001a90535060049490941c9361130681611d7a565b9050611298565b50831561078a5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610840565b80356001600160a01b038116811461137357600080fd5b919050565b60008083601f84011261138a57600080fd5b5081356001600160401b038111156113a157600080fd5b6020830191508360208285010111156113b957600080fd5b9250929050565b600080600080600080600060c0888a0312156113db57600080fd5b6113e48861135c565b96506020880135955060408801356001600160401b0381111561140657600080fd5b6114128a828b01611378565b989b979a50986060810135976080820135975060a09091013595509350505050565b60006020828403121561144657600080fd5b81356001600160e01b03198116811461078a57600080fd5b60008060008060008060a0878903121561147757600080fd5b6114808761135c565b95506020870135945060408701356001600160401b038111156114a257600080fd5b6114ae89828a01611378565b979a9699509760608101359660809091013595509350505050565b6000602082840312156114db57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715611520576115206114e2565b604052919050565b600082601f83011261153957600080fd5b81356001600160401b03811115611552576115526114e2565b611565601f8201601f19166020016114f8565b81815284602083860101111561157a57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156115ad57600080fd5b6115b68561135c565b93506115c46020860161135c565b92506040850135915060608501356001600160401b038111156115e657600080fd5b6115f287828801611528565b91505092959194509250565b6000806040838503121561161157600080fd5b823591506116216020840161135c565b90509250929050565b60008083601f84011261163c57600080fd5b5081356001600160401b0381111561165357600080fd5b6020830191508360208260051b85010111156113b957600080fd5b600080600080600080600080600060c08a8c03121561168c57600080fd5b89356001600160401b03808211156116a357600080fd5b6116af8d838e0161162a565b909b50995060208c01359150808211156116c857600080fd5b6116d48d838e0161162a565b909950975060408c01359150808211156116ed57600080fd5b506116fa8c828d0161162a565b9a9d999c50979a969997986060880135976080810135975060a0013595509350505050565b60008060008060008060008060a0898b03121561173b57600080fd5b88356001600160401b038082111561175257600080fd5b61175e8c838d0161162a565b909a50985060208b013591508082111561177757600080fd5b6117838c838d0161162a565b909850965060408b013591508082111561179c57600080fd5b506117a98b828c0161162a565b999c989b509699959896976060870135966080013595509350505050565b600082601f8301126117d857600080fd5b813560206001600160401b038211156117f3576117f36114e2565b8160051b6118028282016114f8565b928352848101820192828101908785111561181c57600080fd5b83870192505b8483101561183b57823582529183019190830190611822565b979650505050505050565b600080600080600060a0868803121561185e57600080fd5b6118678661135c565b94506118756020870161135c565b935060408601356001600160401b038082111561189157600080fd5b61189d89838a016117c7565b945060608801359150808211156118b357600080fd5b6118bf89838a016117c7565b935060808801359150808211156118d557600080fd5b506118e288828901611528565b9150509295509295909350565b600080600080600060a0868803121561190757600080fd5b6119108661135c565b945061191e6020870161135c565b9350604086013592506060860135915060808601356001600160401b0381111561194757600080fd5b6118e288828901611528565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60018060a01b038716815285602082015260a0604082015260006119a460a083018688611953565b60608301949094525060800152949350505050565b60018060a01b03851681528360208201526060604082015260006119e1606083018486611953565b9695505050505050565b60208082526023908201527f54696d656c6f636b436f6e74726f6c6c65723a206c656e677468206d69736d616040820152620e8c6d60eb1b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215611a5657600080fd5b61078a8261135c565b6000808335601e19843603018112611a7657600080fd5b8301803591506001600160401b03821115611a9057600080fd5b6020019150368190038213156113b957600080fd5b634e487b7160e01b600052601160045260246000fd5b6000600019821415611acf57611acf611aa5565b5060010190565b81835260006020808501808196508560051b810191508460005b87811015611b595782840389528135601e19883603018112611b1157600080fd5b870180356001600160401b03811115611b2957600080fd5b803603891315611b3857600080fd5b611b458682898501611953565b9a87019a9550505090840190600101611af0565b5091979650505050505050565b60a0808252810188905260008960c08301825b8b811015611ba7576001600160a01b03611b928461135c565b16825260209283019290910190600101611b79565b5083810360208501528881526001600160fb1b03891115611bc757600080fd5b8860051b9150818a602083013781810191505060208101600081526020848303016040850152611bf881888a611ad6565b6060850196909652505050608001529695505050505050565b60008219821115611c2457611c24611aa5565b500190565b60005b83811015611c44578181015183820152602001611c2c565b83811115611c53576000848401525b50505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c91816017850160208801611c29565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611cc2816028840160208801611c29565b01602801949350505050565b6020815260008251806020840152611ced816040850160208701611c29565b601f01601f19169190910160400192915050565b6020808252602a908201527f54696d656c6f636b436f6e74726f6c6c65723a206f7065726174696f6e206973604082015269206e6f7420726561647960b01b606082015260800190565b8183823760009101908152919050565b6000816000190483118215151615611d7557611d75611aa5565b500290565b600081611d8957611d89611aa5565b50600019019056fea2646970667358221220dca2012434ae0ee932ca779f9ca2670c90f60d6e9240e5d6e19d5d2d78265ff464736f6c634300080b0033", + "devdoc": { + "details": "Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied. By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer. _Available since v3.3._", + "events": { + "CallExecuted(bytes32,uint256,address,uint256,bytes)": { + "details": "Emitted when a call is performed as part of operation `id`." + }, + "CallScheduled(bytes32,uint256,address,uint256,bytes,bytes32,uint256)": { + "details": "Emitted when a call is scheduled as part of operation `id`." + }, + "Cancelled(bytes32)": { + "details": "Emitted when operation `id` is cancelled." + }, + "MinDelayChange(uint256,uint256)": { + "details": "Emitted when the minimum delay for future operations is modified." + } + }, + "kind": "dev", + "methods": { + "cancel(bytes32)": { + "details": "Cancel an operation. Requirements: - the caller must have the 'canceller' role." + }, + "constructor": { + "details": "Initializes the contract with the following parameters: - `minDelay`: initial minimum delay for operations - `proposers`: accounts to be granted proposer and canceller roles - `executors`: accounts to be granted executor role - `admin`: optional account to be granted admin role; disable with zero address IMPORTANT: The optional admin can aid with initial configuration of roles after deployment without being subject to delay, but this role should be subsequently renounced in favor of administration through timelocked proposals. Previous versions of this contract would assign this admin to the deployer automatically and should be renounced as well." + }, + "execute(address,uint256,bytes,bytes32,bytes32)": { + "details": "Execute an (ready) operation containing a single transaction. Emits a {CallExecuted} event. Requirements: - the caller must have the 'executor' role." + }, + "executeBatch(address[],uint256[],bytes[],bytes32,bytes32)": { + "details": "Execute an (ready) operation containing a batch of transactions. Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' role." + }, + "getMinDelay()": { + "details": "Returns the minimum delay for an operation to become valid. This value can be changed by executing an operation that calls `updateDelay`." + }, + "getRoleAdmin(bytes32)": { + "details": "Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}." + }, + "getTimestamp(bytes32)": { + "details": "Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations)." + }, + "grantRole(bytes32,address)": { + "details": "Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event." + }, + "hasRole(bytes32,address)": { + "details": "Returns `true` if `account` has been granted `role`." + }, + "hashOperation(address,uint256,bytes,bytes32,bytes32)": { + "details": "Returns the identifier of an operation containing a single transaction." + }, + "hashOperationBatch(address[],uint256[],bytes[],bytes32,bytes32)": { + "details": "Returns the identifier of an operation containing a batch of transactions." + }, + "isOperation(bytes32)": { + "details": "Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations." + }, + "isOperationDone(bytes32)": { + "details": "Returns whether an operation is done or not." + }, + "isOperationPending(bytes32)": { + "details": "Returns whether an operation is pending or not." + }, + "isOperationReady(bytes32)": { + "details": "Returns whether an operation is ready or not." + }, + "onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)": { + "details": "See {IERC1155Receiver-onERC1155BatchReceived}." + }, + "onERC1155Received(address,address,uint256,uint256,bytes)": { + "details": "See {IERC1155Receiver-onERC1155Received}." + }, + "onERC721Received(address,address,uint256,bytes)": { + "details": "See {IERC721Receiver-onERC721Received}." + }, + "renounceRole(bytes32,address)": { + "details": "Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event." + }, + "revokeRole(bytes32,address)": { + "details": "Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event." + }, + "schedule(address,uint256,bytes,bytes32,bytes32,uint256)": { + "details": "Schedule an operation containing a single transaction. Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role." + }, + "scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256)": { + "details": "Schedule an operation containing a batch of transactions. Emits one {CallScheduled} event per transaction in the batch. Requirements: - the caller must have the 'proposer' role." + }, + "supportsInterface(bytes4)": { + "details": "See {IERC165-supportsInterface}." + }, + "updateDelay(uint256)": { + "details": "Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 45983, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_roles", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_struct(RoleData)45978_storage)" + }, + { + "astId": 46697, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_timestamps", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_bytes32,t_uint256)" + }, + { + "astId": 46699, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "_minDelay", + "offset": 0, + "slot": "2", + "type": "t_uint256" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_bool)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => bool)", + "numberOfBytes": "32", + "value": "t_bool" + }, + "t_mapping(t_bytes32,t_struct(RoleData)45978_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => struct AccessControl.RoleData)", + "numberOfBytes": "32", + "value": "t_struct(RoleData)45978_storage" + }, + "t_mapping(t_bytes32,t_uint256)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_struct(RoleData)45978_storage": { + "encoding": "inplace", + "label": "struct AccessControl.RoleData", + "members": [ + { + "astId": 45975, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "members", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_bool)" + }, + { + "astId": 45977, + "contract": "contracts/admin/TimelockController.sol:TimelockController", + "label": "adminRole", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/UniswapPricingHelper.json b/packages/contracts/deployments/apechain/UniswapPricingHelper.json new file mode 100644 index 000000000..6f64bd8a1 --- /dev/null +++ b/packages/contracts/deployments/apechain/UniswapPricingHelper.json @@ -0,0 +1,133 @@ +{ + "address": "0x8AAdB10450dc7E9814AB77bdAD8A96f006AEBff0", + "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": "0x83624574017109d544b8dde552b532e7c6f6fbd770dbf4ab639d5140bd621069", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x8AAdB10450dc7E9814AB77bdAD8A96f006AEBff0", + "transactionIndex": 1, + "gasUsed": "923896", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x0770eb773148e7e11b044501f0786287b2626711101f65b43bd78464e4b09174", + "transactionHash": "0x83624574017109d544b8dde552b532e7c6f6fbd770dbf4ab639d5140bd621069", + "logs": [], + "blockNumber": 33944620, + "cumulativeGasUsed": "923896", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/price_oracles/UniswapPricingHelper.sol\":\"UniswapPricingHelper\"},\"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/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\"},\"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/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\"},\"contracts/price_oracles/UniswapPricingHelper.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\n\\n//import \\\"forge-std/console.sol\\\";\\n \\n\\nimport {IUniswapPricingLibrary} from \\\"../interfaces/IUniswapPricingLibrary.sol\\\";\\n\\n \\n \\n// Libraries \\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 \\n*/\\n\\ncontract UniswapPricingHelper\\n{\\n\\n\\n // use uniswap exp helper instead ? \\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\\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x5588c1215275d954f5c2a4602844b78a67794780936fff363c749721cb1a8e49\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b50610fc1806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80633bbe42751461003b578063a1a73faf14610060575b600080fd5b61004e610049366004610aec565b610073565b60405190815260200160405180910390f35b61004e61006e366004610b8b565b61015d565b60006002825111156100cc5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101325760006100fb836000815181106100ee576100ee610ba7565b602002602001015161015d565b90506000610115846001815181106100ee576100ee610ba7565b905061012a8282670de0b6b3a764000061018e565b949350505050565b81516001141561015857610152826000815181106100ee576100ee610ba7565b92915050565b919050565b6000806101728360000151846040015161030a565b60208401519091501561012a82670de0b6b3a7640000836104e1565b6000808060001985870985870292508281108382030391505080600014156101c857600084116101bd57600080fd5b508290049050610303565b8084116101d457600080fd5b6000848688098084039381119092039190506000856101f581196001610bd3565b169586900495938490049360008190030460010190506102158184610beb565b909317926000610226876003610beb565b60021890506102358188610beb565b610240906002610c0a565b61024a9082610beb565b90506102568188610beb565b610261906002610c0a565b61026b9082610beb565b90506102778188610beb565b610282906002610c0a565b61028c9082610beb565b90506102988188610beb565b6102a3906002610c0a565b6102ad9082610beb565b90506102b98188610beb565b6102c4906002610c0a565b6102ce9082610beb565b90506102da8188610beb565b6102e5906002610c0a565b6102ef9082610beb565b90506102fb8186610beb565b955050505050505b9392505050565b600063ffffffff821661038857826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610355573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103799190610c33565b50949550610152945050505050565b6040805160028082526060820183526000926020830190803683370190505090506103b4836001610cd2565b816000815181106103c7576103c7610ba7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106103f6576103f6610ba7565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd9061043a908590600401610cfa565b600060405180830381865afa158015610457573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261047f9190810190610db3565b5090506104d88460030b8260008151811061049c5761049c610ba7565b6020026020010151836001815181106104b7576104b7610ba7565b60200260200101516104c99190610e7f565b6104d39190610ee5565b6105b0565b95945050505050565b60006001600160801b036001600160a01b0385161161055457600061050f6001600160a01b03861680610beb565b905082156105345761052f600160c01b856001600160801b03168361018e565b61054c565b61054c81856001600160801b0316600160c01b61018e565b915050610303565b60006105736001600160a01b038616806801000000000000000061018e565b9050821561059857610593600160801b856001600160801b03168361018e565b6104d8565b6104d881856001600160801b0316600160801b61018e565b60008060008360020b126105c7578260020b6105d4565b8260020b6105d490610f23565b90506105e3620d89e719610f40565b62ffffff1681111561061b5760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064016100c3565b60006001821661062f57600160801b610641565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561068057608061067b826ffff97272373d413259a46990580e213a610beb565b901c90505b60048216156106aa5760806106a5826ffff2e50f5f656932ef12357cf3c7fdcc610beb565b901c90505b60088216156106d45760806106cf826fffe5caca7e10e4e61c3624eaa0941cd0610beb565b901c90505b60108216156106fe5760806106f9826fffcb9843d60f6159c9db58835c926644610beb565b901c90505b6020821615610728576080610723826fff973b41fa98c081472e6896dfb254c0610beb565b901c90505b604082161561075257608061074d826fff2ea16466c96a3843ec78b326b52861610beb565b901c90505b608082161561077c576080610777826ffe5dee046a99a2a811c461f1969c3053610beb565b901c90505b6101008216156107a75760806107a2826ffcbe86c7900a88aedcffc83b479aa3a4610beb565b901c90505b6102008216156107d25760806107cd826ff987a7253ac413176f2b074cf7815e54610beb565b901c90505b6104008216156107fd5760806107f8826ff3392b0822b70005940c7a398e4b70f3610beb565b901c90505b610800821615610828576080610823826fe7159475a2c29b7443b29c7fa6e889d9610beb565b901c90505b61100082161561085357608061084e826fd097f3bdfd2022b8845ad8f792aa5825610beb565b901c90505b61200082161561087e576080610879826fa9f746462d870fdf8a65dc1f90e061e5610beb565b901c90505b6140008216156108a95760806108a4826f70d869a156d2a1b890bb3df62baf32f7610beb565b901c90505b6180008216156108d45760806108cf826f31be135f97d08fd981231505542fcfa6610beb565b901c90505b620100008216156109005760806108fb826f09aa508b5b7a84e1c677de54f3e99bc9610beb565b901c90505b6202000082161561092b576080610926826e5d6af8dedb81196699c329225ee604610beb565b901c90505b62040000821615610955576080610950826d2216e584f5fa1ea926041bedfe98610beb565b901c90505b6208000082161561097d576080610978826b048a170391f7dc42444e8fa2610beb565b901c90505b60008460020b13156109985761099581600019610f63565b90505b6109a764010000000082610f77565b156109b35760016109b6565b60005b61012a9060ff16602083901c610bd3565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a0657610a066109c7565b604052919050565b600067ffffffffffffffff821115610a2857610a286109c7565b5060051b60200190565b6001600160a01b0381168114610a4757600080fd5b50565b8015158114610a4757600080fd5b600060a08284031215610a6a57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a8d57610a8d6109c7565b6040529050808235610a9e81610a32565b81526020830135610aae81610a4a565b6020820152604083013563ffffffff81168114610aca57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b60006020808385031215610aff57600080fd5b823567ffffffffffffffff811115610b1657600080fd5b8301601f81018513610b2757600080fd5b8035610b3a610b3582610a0e565b6109dd565b81815260a09182028301840191848201919088841115610b5957600080fd5b938501935b83851015610b7f57610b708986610a58565b83529384019391850191610b5e565b50979650505050505050565b600060a08284031215610b9d57600080fd5b6103038383610a58565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60008219821115610be657610be6610bbd565b500190565b6000816000190483118215151615610c0557610c05610bbd565b500290565b600082821015610c1c57610c1c610bbd565b500390565b805161ffff8116811461015857600080fd5b600080600080600080600060e0888a031215610c4e57600080fd5b8751610c5981610a32565b8097505060208801518060020b8114610c7157600080fd5b9550610c7f60408901610c21565b9450610c8d60608901610c21565b9350610c9b60808901610c21565b925060a088015160ff81168114610cb157600080fd5b60c0890151909250610cc281610a4a565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610cf157610cf1610bbd565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610d3857835163ffffffff1683529284019291840191600101610d16565b50909695505050505050565b600082601f830112610d5557600080fd5b81516020610d65610b3583610a0e565b82815260059290921b84018101918181019086841115610d8457600080fd5b8286015b84811015610da8578051610d9b81610a32565b8352918301918301610d88565b509695505050505050565b60008060408385031215610dc657600080fd5b825167ffffffffffffffff80821115610dde57600080fd5b818501915085601f830112610df257600080fd5b81516020610e02610b3583610a0e565b82815260059290921b84018101918181019089841115610e2157600080fd5b948201945b83861015610e4f5785518060060b8114610e405760008081fd5b82529482019490820190610e26565b91880151919650909350505080821115610e6857600080fd5b50610e7585828601610d44565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610eaa57610eaa610bbd565b81667fffffffffffff018313811615610ec557610ec5610bbd565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610efc57610efc610ecf565b667fffffffffffff19821460001982141615610f1a57610f1a610bbd565b90059392505050565b6000600160ff1b821415610f3957610f39610bbd565b5060000390565b60008160020b627fffff19811415610f5a57610f5a610bbd565b60000392915050565b600082610f7257610f72610ecf565b500490565b600082610f8657610f86610ecf565b50069056fea2646970667358221220d6fed705ed46d18dae159a22c722e9aeed52e439bd366bf546b78a194cfd204064736f6c634300080b0033", + "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100365760003560e01c80633bbe42751461003b578063a1a73faf14610060575b600080fd5b61004e610049366004610aec565b610073565b60405190815260200160405180910390f35b61004e61006e366004610b8b565b61015d565b60006002825111156100cc5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101325760006100fb836000815181106100ee576100ee610ba7565b602002602001015161015d565b90506000610115846001815181106100ee576100ee610ba7565b905061012a8282670de0b6b3a764000061018e565b949350505050565b81516001141561015857610152826000815181106100ee576100ee610ba7565b92915050565b919050565b6000806101728360000151846040015161030a565b60208401519091501561012a82670de0b6b3a7640000836104e1565b6000808060001985870985870292508281108382030391505080600014156101c857600084116101bd57600080fd5b508290049050610303565b8084116101d457600080fd5b6000848688098084039381119092039190506000856101f581196001610bd3565b169586900495938490049360008190030460010190506102158184610beb565b909317926000610226876003610beb565b60021890506102358188610beb565b610240906002610c0a565b61024a9082610beb565b90506102568188610beb565b610261906002610c0a565b61026b9082610beb565b90506102778188610beb565b610282906002610c0a565b61028c9082610beb565b90506102988188610beb565b6102a3906002610c0a565b6102ad9082610beb565b90506102b98188610beb565b6102c4906002610c0a565b6102ce9082610beb565b90506102da8188610beb565b6102e5906002610c0a565b6102ef9082610beb565b90506102fb8186610beb565b955050505050505b9392505050565b600063ffffffff821661038857826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610355573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103799190610c33565b50949550610152945050505050565b6040805160028082526060820183526000926020830190803683370190505090506103b4836001610cd2565b816000815181106103c7576103c7610ba7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106103f6576103f6610ba7565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd9061043a908590600401610cfa565b600060405180830381865afa158015610457573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261047f9190810190610db3565b5090506104d88460030b8260008151811061049c5761049c610ba7565b6020026020010151836001815181106104b7576104b7610ba7565b60200260200101516104c99190610e7f565b6104d39190610ee5565b6105b0565b95945050505050565b60006001600160801b036001600160a01b0385161161055457600061050f6001600160a01b03861680610beb565b905082156105345761052f600160c01b856001600160801b03168361018e565b61054c565b61054c81856001600160801b0316600160c01b61018e565b915050610303565b60006105736001600160a01b038616806801000000000000000061018e565b9050821561059857610593600160801b856001600160801b03168361018e565b6104d8565b6104d881856001600160801b0316600160801b61018e565b60008060008360020b126105c7578260020b6105d4565b8260020b6105d490610f23565b90506105e3620d89e719610f40565b62ffffff1681111561061b5760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064016100c3565b60006001821661062f57600160801b610641565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561068057608061067b826ffff97272373d413259a46990580e213a610beb565b901c90505b60048216156106aa5760806106a5826ffff2e50f5f656932ef12357cf3c7fdcc610beb565b901c90505b60088216156106d45760806106cf826fffe5caca7e10e4e61c3624eaa0941cd0610beb565b901c90505b60108216156106fe5760806106f9826fffcb9843d60f6159c9db58835c926644610beb565b901c90505b6020821615610728576080610723826fff973b41fa98c081472e6896dfb254c0610beb565b901c90505b604082161561075257608061074d826fff2ea16466c96a3843ec78b326b52861610beb565b901c90505b608082161561077c576080610777826ffe5dee046a99a2a811c461f1969c3053610beb565b901c90505b6101008216156107a75760806107a2826ffcbe86c7900a88aedcffc83b479aa3a4610beb565b901c90505b6102008216156107d25760806107cd826ff987a7253ac413176f2b074cf7815e54610beb565b901c90505b6104008216156107fd5760806107f8826ff3392b0822b70005940c7a398e4b70f3610beb565b901c90505b610800821615610828576080610823826fe7159475a2c29b7443b29c7fa6e889d9610beb565b901c90505b61100082161561085357608061084e826fd097f3bdfd2022b8845ad8f792aa5825610beb565b901c90505b61200082161561087e576080610879826fa9f746462d870fdf8a65dc1f90e061e5610beb565b901c90505b6140008216156108a95760806108a4826f70d869a156d2a1b890bb3df62baf32f7610beb565b901c90505b6180008216156108d45760806108cf826f31be135f97d08fd981231505542fcfa6610beb565b901c90505b620100008216156109005760806108fb826f09aa508b5b7a84e1c677de54f3e99bc9610beb565b901c90505b6202000082161561092b576080610926826e5d6af8dedb81196699c329225ee604610beb565b901c90505b62040000821615610955576080610950826d2216e584f5fa1ea926041bedfe98610beb565b901c90505b6208000082161561097d576080610978826b048a170391f7dc42444e8fa2610beb565b901c90505b60008460020b13156109985761099581600019610f63565b90505b6109a764010000000082610f77565b156109b35760016109b6565b60005b61012a9060ff16602083901c610bd3565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a0657610a066109c7565b604052919050565b600067ffffffffffffffff821115610a2857610a286109c7565b5060051b60200190565b6001600160a01b0381168114610a4757600080fd5b50565b8015158114610a4757600080fd5b600060a08284031215610a6a57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a8d57610a8d6109c7565b6040529050808235610a9e81610a32565b81526020830135610aae81610a4a565b6020820152604083013563ffffffff81168114610aca57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b60006020808385031215610aff57600080fd5b823567ffffffffffffffff811115610b1657600080fd5b8301601f81018513610b2757600080fd5b8035610b3a610b3582610a0e565b6109dd565b81815260a09182028301840191848201919088841115610b5957600080fd5b938501935b83851015610b7f57610b708986610a58565b83529384019391850191610b5e565b50979650505050505050565b600060a08284031215610b9d57600080fd5b6103038383610a58565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b60008219821115610be657610be6610bbd565b500190565b6000816000190483118215151615610c0557610c05610bbd565b500290565b600082821015610c1c57610c1c610bbd565b500390565b805161ffff8116811461015857600080fd5b600080600080600080600060e0888a031215610c4e57600080fd5b8751610c5981610a32565b8097505060208801518060020b8114610c7157600080fd5b9550610c7f60408901610c21565b9450610c8d60608901610c21565b9350610c9b60808901610c21565b925060a088015160ff81168114610cb157600080fd5b60c0890151909250610cc281610a4a565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610cf157610cf1610bbd565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610d3857835163ffffffff1683529284019291840191600101610d16565b50909695505050505050565b600082601f830112610d5557600080fd5b81516020610d65610b3583610a0e565b82815260059290921b84018101918181019086841115610d8457600080fd5b8286015b84811015610da8578051610d9b81610a32565b8352918301918301610d88565b509695505050505050565b60008060408385031215610dc657600080fd5b825167ffffffffffffffff80821115610dde57600080fd5b818501915085601f830112610df257600080fd5b81516020610e02610b3583610a0e565b82815260059290921b84018101918181019089841115610e2157600080fd5b948201945b83861015610e4f5785518060060b8114610e405760008081fd5b82529482019490820190610e26565b91880151919650909350505080821115610e6857600080fd5b50610e7585828601610d44565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610eaa57610eaa610bbd565b81667fffffffffffff018313811615610ec557610ec5610bbd565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610efc57610efc610ecf565b667fffffffffffff19821460001982141615610f1a57610f1a610bbd565b90059392505050565b6000600160ff1b821415610f3957610f39610bbd565b5060000390565b60008160020b627fffff19811415610f5a57610f5a610bbd565b60000392915050565b600082610f7257610f72610ecf565b500490565b600082610f8657610f86610ecf565b50069056fea2646970667358221220d6fed705ed46d18dae159a22c722e9aeed52e439bd366bf546b78a194cfd204064736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/UniswapPricingLibrary.json b/packages/contracts/deployments/apechain/UniswapPricingLibrary.json new file mode 100644 index 000000000..4dc5fdf47 --- /dev/null +++ b/packages/contracts/deployments/apechain/UniswapPricingLibrary.json @@ -0,0 +1,133 @@ +{ + "address": "0xfDDcEc68cfa40c38Faf05F918484fC416a221BFF", + "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": "0xa19be8c4ef60fb13667e68f87c56c7bf49b68d1e19f87872a90f98993fcff666", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xfDDcEc68cfa40c38Faf05F918484fC416a221BFF", + "transactionIndex": 1, + "gasUsed": "905102", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x3b9b4d10b463c743e48c3927b123cf42e1c24f198febd317b62ac6642cdab4ff", + "transactionHash": "0xa19be8c4ef60fb13667e68f87c56c7bf49b68d1e19f87872a90f98993fcff666", + "logs": [], + "blockNumber": 33944600, + "cumulativeGasUsed": "905102", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/UniswapPricingLibrary.sol\":\"UniswapPricingLibrary\"},\"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/UniswapPricingLibrary.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 UniswapPricingLibrary \\n{\\n \\n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRouteConfig.pool,\\n _poolRouteConfig.twapInterval\\n );\\n\\n //This is the token 1 per token 0 price\\n uint256 sqrtPrice = FullMath.mulDiv(\\n sqrtPriceX96,\\n STANDARD_EXPANSION_FACTOR,\\n 2**96\\n );\\n\\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\\n\\n uint256 price = _poolRouteConfig.zeroForOne\\n ? sqrtPrice * sqrtPrice\\n : sqrtPriceInverse * sqrtPriceInverse;\\n\\n return price / STANDARD_EXPANSION_FACTOR;\\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\":\"0x89fa90d3bba54e357a693f9e0ea96920edfd60c16f8a6a77a32892f4cafd60f3\",\"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": "0x610f6961003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610a70565b61007d565b60405190815260200160405180910390f35b610058610078366004610ab0565b61011b565b60008061009283600001518460400151610205565b905060006100b6826001600160a01b0316670de0b6b3a7640000600160601b6103dc565b90506000816100cd670de0b6b3a764000080610b65565b6100d79190610b9a565b9050600085602001516100f3576100ee8280610b65565b6100fd565b6100fd8380610b65565b9050610111670de0b6b3a764000082610b9a565b9695505050505050565b60006002825111156101745760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b8151600214156101da5760006101a38360008151811061019657610196610bae565b602002602001015161007d565b905060006101bd8460018151811061019657610196610bae565b90506101d28282670de0b6b3a76400006103dc565b949350505050565b815160011415610200576101fa8260008151811061019657610196610bae565b92915050565b919050565b600063ffffffff821661028357826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa158015610250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102749190610bd6565b509495506101fa945050505050565b6040805160028082526060820183526000926020830190803683370190505090506102af836001610c75565b816000815181106102c2576102c2610bae565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106102f1576102f1610bae565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd90610335908590600401610c9d565b600060405180830381865afa158015610352573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261037a9190810190610d56565b5090506103d38460030b8260008151811061039757610397610bae565b6020026020010151836001815181106103b2576103b2610bae565b60200260200101516103c49190610e22565b6103ce9190610e72565b610558565b95945050505050565b600080806000198587098587029250828110838203039150508060001415610416576000841161040b57600080fd5b508290049050610551565b80841161042257600080fd5b60008486880980840393811190920391905060008561044381196001610eb0565b169586900495938490049360008190030460010190506104638184610b65565b909317926000610474876003610b65565b60021890506104838188610b65565b61048e906002610ec8565b6104989082610b65565b90506104a48188610b65565b6104af906002610ec8565b6104b99082610b65565b90506104c58188610b65565b6104d0906002610ec8565b6104da9082610b65565b90506104e68188610b65565b6104f1906002610ec8565b6104fb9082610b65565b90506105078188610b65565b610512906002610ec8565b61051c9082610b65565b90506105288188610b65565b610533906002610ec8565b61053d9082610b65565b90506105498186610b65565b955050505050505b9392505050565b60008060008360020b1261056f578260020b61057c565b8260020b61057c90610edf565b905061058b620d89e719610efc565b62ffffff168111156105c35760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640161016b565b6000600182166105d757600160801b6105e9565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610628576080610623826ffff97272373d413259a46990580e213a610b65565b901c90505b600482161561065257608061064d826ffff2e50f5f656932ef12357cf3c7fdcc610b65565b901c90505b600882161561067c576080610677826fffe5caca7e10e4e61c3624eaa0941cd0610b65565b901c90505b60108216156106a65760806106a1826fffcb9843d60f6159c9db58835c926644610b65565b901c90505b60208216156106d05760806106cb826fff973b41fa98c081472e6896dfb254c0610b65565b901c90505b60408216156106fa5760806106f5826fff2ea16466c96a3843ec78b326b52861610b65565b901c90505b608082161561072457608061071f826ffe5dee046a99a2a811c461f1969c3053610b65565b901c90505b61010082161561074f57608061074a826ffcbe86c7900a88aedcffc83b479aa3a4610b65565b901c90505b61020082161561077a576080610775826ff987a7253ac413176f2b074cf7815e54610b65565b901c90505b6104008216156107a55760806107a0826ff3392b0822b70005940c7a398e4b70f3610b65565b901c90505b6108008216156107d05760806107cb826fe7159475a2c29b7443b29c7fa6e889d9610b65565b901c90505b6110008216156107fb5760806107f6826fd097f3bdfd2022b8845ad8f792aa5825610b65565b901c90505b612000821615610826576080610821826fa9f746462d870fdf8a65dc1f90e061e5610b65565b901c90505b61400082161561085157608061084c826f70d869a156d2a1b890bb3df62baf32f7610b65565b901c90505b61800082161561087c576080610877826f31be135f97d08fd981231505542fcfa6610b65565b901c90505b620100008216156108a85760806108a3826f09aa508b5b7a84e1c677de54f3e99bc9610b65565b901c90505b620200008216156108d35760806108ce826e5d6af8dedb81196699c329225ee604610b65565b901c90505b620400008216156108fd5760806108f8826d2216e584f5fa1ea926041bedfe98610b65565b901c90505b62080000821615610925576080610920826b048a170391f7dc42444e8fa2610b65565b901c90505b60008460020b13156109405761093d81600019610b9a565b90505b61094f64010000000082610f1f565b1561095b57600161095e565b60005b6101d29060ff16602083901c610eb0565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109ae576109ae61096f565b604052919050565b6001600160a01b03811681146109cb57600080fd5b50565b80151581146109cb57600080fd5b600060a082840312156109ee57600080fd5b60405160a0810181811067ffffffffffffffff82111715610a1157610a1161096f565b6040529050808235610a22816109b6565b81526020830135610a32816109ce565b6020820152604083013563ffffffff81168114610a4e57600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610a8257600080fd5b61055183836109dc565b600067ffffffffffffffff821115610aa657610aa661096f565b5060051b60200190565b60006020808385031215610ac357600080fd5b823567ffffffffffffffff811115610ada57600080fd5b8301601f81018513610aeb57600080fd5b8035610afe610af982610a8c565b610985565b81815260a09182028301840191848201919088841115610b1d57600080fd5b938501935b83851015610b4357610b3489866109dc565b83529384019391850191610b22565b50979650505050505050565b634e487b7160e01b600052601160045260246000fd5b6000816000190483118215151615610b7f57610b7f610b4f565b500290565b634e487b7160e01b600052601260045260246000fd5b600082610ba957610ba9610b84565b500490565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461020057600080fd5b600080600080600080600060e0888a031215610bf157600080fd5b8751610bfc816109b6565b8097505060208801518060020b8114610c1457600080fd5b9550610c2260408901610bc4565b9450610c3060608901610bc4565b9350610c3e60808901610bc4565b925060a088015160ff81168114610c5457600080fd5b60c0890151909250610c65816109ce565b8091505092959891949750929550565b600063ffffffff808316818516808303821115610c9457610c94610b4f565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cdb57835163ffffffff1683529284019291840191600101610cb9565b50909695505050505050565b600082601f830112610cf857600080fd5b81516020610d08610af983610a8c565b82815260059290921b84018101918181019086841115610d2757600080fd5b8286015b84811015610d4b578051610d3e816109b6565b8352918301918301610d2b565b509695505050505050565b60008060408385031215610d6957600080fd5b825167ffffffffffffffff80821115610d8157600080fd5b818501915085601f830112610d9557600080fd5b81516020610da5610af983610a8c565b82815260059290921b84018101918181019089841115610dc457600080fd5b948201945b83861015610df25785518060060b8114610de35760008081fd5b82529482019490820190610dc9565b91880151919650909350505080821115610e0b57600080fd5b50610e1885828601610ce7565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e4d57610e4d610b4f565b81667fffffffffffff018313811615610e6857610e68610b4f565b5090039392505050565b60008160060b8360060b80610e8957610e89610b84565b667fffffffffffff19821460001982141615610ea757610ea7610b4f565b90059392505050565b60008219821115610ec357610ec3610b4f565b500190565b600082821015610eda57610eda610b4f565b500390565b6000600160ff1b821415610ef557610ef5610b4f565b5060000390565b60008160020b627fffff19811415610f1657610f16610b4f565b60000392915050565b600082610f2e57610f2e610b84565b50069056fea26469706673582212202661aff493f8f9b94f15f3b6e68ec96d37b6de56abcee711d4d4ed423057375464736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/UniswapPricingLibraryV2.json b/packages/contracts/deployments/apechain/UniswapPricingLibraryV2.json new file mode 100644 index 000000000..94fa6c11a --- /dev/null +++ b/packages/contracts/deployments/apechain/UniswapPricingLibraryV2.json @@ -0,0 +1,133 @@ +{ + "address": "0x203ee2F172826Fa46A175230DF260188fE0C96Fc", + "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": "0x29b2c7fe6d0af112842de3989bb1fbd8ca36925650a4628c5762ce77364f3127", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x203ee2F172826Fa46A175230DF260188fE0C96Fc", + "transactionIndex": 1, + "gasUsed": "928251", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xfed2dce17bc350db319c7da8e391287ddb2a14579402ef80addcf87211014f7a", + "transactionHash": "0x29b2c7fe6d0af112842de3989bb1fbd8ca36925650a4628c5762ce77364f3127", + "logs": [], + "blockNumber": 33944601, + "cumulativeGasUsed": "928251", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "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/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\"},\"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\\n \\n \\n// Libraries \\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 /**\\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). Taken directly from uniswap oracle lib \\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\":\"0x8d3fc2a832e4d6af64a0bd3a94aa3b86fe2324b95b702d196bc053c4b4e334e1\",\"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": "0x610fd461003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea2646970667358221220a7c1d9bbf646b2578e11d57f61d6d5745c38d44cc620fab99a27eb95b03679e464736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/V2Calculations.json b/packages/contracts/deployments/apechain/V2Calculations.json new file mode 100644 index 000000000..961e8f916 --- /dev/null +++ b/packages/contracts/deployments/apechain/V2Calculations.json @@ -0,0 +1,149 @@ +{ + "address": "0x5d3eCF8877eDAB28e14bD7d243fA8B0fE416E95E", + "abi": [ + { + "inputs": [ + { + "internalType": "uint32", + "name": "_acceptedTimestamp", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_paymentCycle", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_loanDuration", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_lastRepaidTimestamp", + "type": "uint32" + }, + { + "internalType": "enum PaymentCycleType", + "name": "_bidPaymentCycleType", + "type": "PaymentCycleType" + } + ], + "name": "calculateNextDueDate", + "outputs": [ + { + "internalType": "uint32", + "name": "dueDate_", + "type": "uint32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "enum PaymentType", + "name": "_type", + "type": "PaymentType" + }, + { + "internalType": "enum PaymentCycleType", + "name": "_cycleType", + "type": "PaymentCycleType" + }, + { + "internalType": "uint256", + "name": "_principal", + "type": "uint256" + }, + { + "internalType": "uint32", + "name": "_duration", + "type": "uint32" + }, + { + "internalType": "uint32", + "name": "_paymentCycle", + "type": "uint32" + }, + { + "internalType": "uint16", + "name": "_apr", + "type": "uint16" + } + ], + "name": "calculatePaymentCycleAmount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + } + ], + "transactionHash": "0x4748dbb1714c9460146c740d817ee70005a7f71313a3219ee7d4d94518a0becf", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x5d3eCF8877eDAB28e14bD7d243fA8B0fE416E95E", + "transactionIndex": 1, + "gasUsed": "1135271", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x7d42f2fdb912702dbc991a390ebbdc44c7b029c000d2993fb63a30dae662d26f", + "transactionHash": "0x4748dbb1714c9460146c740d817ee70005a7f71313a3219ee7d4d94518a0becf", + "logs": [], + "blockNumber": 33944571, + "cumulativeGasUsed": "1135271", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "0734360f150a1a42bdf38edcad8bf3ab", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint32\",\"name\":\"_acceptedTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_loanDuration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_lastRepaidTimestamp\",\"type\":\"uint32\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_bidPaymentCycleType\",\"type\":\"PaymentCycleType\"}],\"name\":\"calculateNextDueDate\",\"outputs\":[{\"internalType\":\"uint32\",\"name\":\"dueDate_\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"enum PaymentType\",\"name\":\"_type\",\"type\":\"PaymentType\"},{\"internalType\":\"enum PaymentCycleType\",\"name\":\"_cycleType\",\"type\":\"PaymentCycleType\"},{\"internalType\":\"uint256\",\"name\":\"_principal\",\"type\":\"uint256\"},{\"internalType\":\"uint32\",\"name\":\"_duration\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"_paymentCycle\",\"type\":\"uint32\"},{\"internalType\":\"uint16\",\"name\":\"_apr\",\"type\":\"uint16\"}],\"name\":\"calculatePaymentCycleAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"params\":{\"_bid\":\"The loan bid struct to get the owed amount for.\",\"_paymentCycleType\":\"The payment cycle type of the loan (Seconds or Monthly).\",\"_timestamp\":\"The timestamp at which to get the owed amount at.\"}},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"params\":{\"_apr\":\"The annual percentage rate of the loan.\",\"_cycleType\":\"The cycle type set for the loan. (Seconds or Monthly)\",\"_duration\":\"The length of the loan.\",\"_paymentCycle\":\"The length of the loan's payment cycle.\",\"_principal\":\"The starting amount that is owed on the loan.\",\"_type\":\"The payment type of the loan.\"}}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{\"calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)\":{\"notice\":\"Calculates the amount owed for a loan.\"},\"calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)\":{\"notice\":\"Calculates the amount owed for a loan for the next payment cycle.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/V2Calculations.sol\":\"V2Calculations\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@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\",\"keccak256\":\"0x2c0b89cef83f353c6f9488c013d8a5968587ffdd6dfc26aad53774214b97e229\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc6cef87559d0aeffdf0a99803de655938a7779ec0a3cd5d4383483ad85565a09\",\"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\"},\"@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\",\"keccak256\":\"0x52a8cfb0f5239d11b457dcdd1b326992ef672714ca8da71a157255bddd13f3ad\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x0f633a0223d9a1dcccfcf38a64c9de0874dfcbfac0c6941ccf074d63a2ce0e1e\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0xc3ff3f5c4584e1d9a483ad7ced51ab64523201f4e3d3c65293e4ca8aeb77a961\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x5a41ca49530d1b4697b5ea58b02900a3297b42a84e49c2753a55b5939c84a415\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x30aabe18188500137c312a4645ae5030e6edbb73ca3a04141b18f4f9a65aec62\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2e4bcf4a965f840193af8729251386c1826cd050411ba4a9e85984a2551fd2ff\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x74752921f592df45c8717d7084627e823b1dbc93bad7187cd3023c9690df7e60\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xfce671ea099d9f997a69c3447eb4a9c9693d37c5b97e43ada376e614e1c7cb61\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x58734812c9549a2d53d86ac6349b2fba615460732145e863ef9d0c8dc3712d08\"},\"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\",\"keccak256\":\"0x5db90829269f806ed14a6c638f38d4aac1fa0f85829b34a2fcddd5200261c148\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xeca3ac3bacec52af15b2c86c5bf1a1be315aade51fa86f95da2b426b28486b1e\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x7d80ce49d143f2f509e1992ed41200e07376bea48950e3674db71a343882f2c8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xceb1ea2ef4c6e2ad7986db84de49c959e8d59844563d27daca5b8d78b732a8f7\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2a17561a47cb3517f2820d68d9bbcd86dcd21c59cad7208581004ecd91d5478a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8d6e50fd460912231e53135b4459aa2f6f16007ae8deb32bc2cee1e88311a8d8\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0xc5b554eea7e17e47acc632cab40894bac2d2699864fdccc61e08fa8f546c0437\"},\"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\",\"keccak256\":\"0xf194df8ea9946a5bb3300223629b7e4959c1f20bacba27b3dc5f6dd2a160147a\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x78009ffb3737ab7615a1e38a26635d6c06b65b7b7959af46d6ef840d220e70cf\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x8452535763bfb5c529a0089b8b669d77cc4e1e333b526b89b5d42ab491fb4312\",\"license\":\"MIT\"},\"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\",\"keccak256\":\"0x2781319be7a96f56966c601c061849fa94dbf9af5ad80a20c40b879a8d03f14a\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x61139261003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100555760003560e01c80628945b51461005a5780630dcf1658146100805780635ab17296146100a8578063e4de10d3146100d6575b600080fd5b61006d610068366004610e66565b6100e9565b6040519081526020015b60405180910390f35b61009361008e366004610ee2565b610187565b60405163ffffffff9091168152602001610077565b6100bb6100b6366004610f4b565b6102bd565b60408051938452602084019290925290820152606001610077565b6100bb6100e4366004610f9d565b6104a8565b600080600187600181111561010057610100610fe5565b1461010f576301e13380610115565b6301da9c005b63ffffffff169050600188600181111561013157610131610fe5565b141561016c5761016461015163ffffffff808716908490600a906104d816565b600a61015d898761050f565b919061052a565b91505061017d565b610179868686868561053f565b9150505b9695505050505050565b6000600182600181111561019d5761019d610fe5565b14156102195760006101bb8763ffffffff168563ffffffff16610674565b90506101cc8763ffffffff166106fb565b6101db8563ffffffff166106fb565b11156101f3576101ec600282611011565b9050610201565b6101fe600182611011565b90505b6102118763ffffffff1682610715565b91505061028d565b600082600181111561022d5761022d610fe5565b141561028d5761023d8587611029565b9050600061024b8785611051565b905063ffffffff81161561028b5760006102718263ffffffff168863ffffffff166107e7565b905061027d8782611076565b6102879084611029565b9250505b505b60006102998588611029565b90508063ffffffff168263ffffffff1611156102b3578091505b5095945050505050565b60078501546006860154600091829182916102d7916110a2565b925060006102e588886110a2565b9050600060018760018111156102fd576102fd610fe5565b1461030c576301e13380610312565b6301da9c005b600b8b015463ffffffff918216925060009161034191889164010000000090910461ffff169060029061052a16565b90508161034e84836110b9565b61035891906110ee565b60098c01549094506000925082915061037f908890600160601b900463ffffffff16611102565b63ffffffff16905080610395575063ffffffff86165b60098b01546000906103be9063ffffffff600160601b8204811691640100000000900416611011565b905060006103cc83836110a2565b9050808b11806103e95750600a8d01546103e6878a611011565b11155b9350600192506103f7915050565b600c8b0154610100900460ff16600181111561041557610415610fe5565b141561042a578015610425578493505b61049b565b60006104688763ffffffff16848d600a016000015461044991906110b9565b61045391906110ee565b600a8d0154610463908790611011565b61081e565b90506000826104775781610481565b6104818588611011565b905061049661049086836110a2565b8861081e565b955050505b5050955095509592505050565b60008060006104c8876104ba89610834565b63ffffffff168888886102bd565b9250925092509450945094915050565b6000826104e757506000610508565b826104f18361087b565b6104fb90866110b9565b61050591906110ee565b90505b9392505050565b6000610521838361ffff16600261052a565b90505b92915050565b60006105358261087b565b6104fb84866110b9565b60008363ffffffff168563ffffffff1610156105ad5760405162461bcd60e51b815260206004820152602360248201527f504d543a206379636c65206475726174696f6e203c206c6f616e20647572617460448201526234b7b760e91b606482015260840160405180910390fd5b61ffff83166105d6576105cf868563ffffffff168763ffffffff166001610893565b905061066b565b60006105ee8663ffffffff168663ffffffff166107e7565b9050670de0b6b3a7640000600061061e8561061863ffffffff8a166106128a6108e4565b90610908565b9061093c565b90506000610636846106308486611011565b9061096c565b90506000610648826106128d86610908565b9050600061065685846110a2565b9050610662828261093c565b96505050505050505b95945050505050565b60008183111561068357600080fd5b60008061069b61069662015180876110ee565b610984565b5090925090506000806106b461069662015180886110ee565b509092509050826106c685600c6110b9565b826106d285600c6110b9565b6106dc9190611011565b6106e691906110a2565b6106f091906110a2565b979650505050505050565b600061070d61069662015180846110ee565b949350505050565b600080808061072a61069662015180886110ee565b9194509250905061073b8583611011565b9150600c61074a6001846110a2565b61075491906110ee565b61075e9084611011565b9250600c61076d6001846110a2565b6107779190611125565b610782906001611011565b915060006107908484610af8565b90508082111561079e578091505b6107ab6201518088611125565b620151806107ba868686610b7e565b6107c491906110b9565b6107ce9190611011565b9450868510156107dd57600080fd5b5050505092915050565b6000821561081557816107fb6001856110a2565b61080591906110ee565b610810906001611011565b610521565b50600092915050565b600081831061082d5781610521565b5090919050565b6009810154600090600160401b900463ffffffff1615610865576009820154600160401b900463ffffffff16610524565b5060090154640100000000900463ffffffff1690565b600061088882600a61121d565b6105249060646110b9565b6000806108a1868686610cbb565b905060018360028111156108b7576108b7610fe5565b1480156108d45750600084806108cf576108cf6110d8565b868809115b1561066b5761017d600182611011565b600061052461271061090261ffff8516670de0b6b3a7640000610d6b565b90610d77565b6000610521670de0b6b3a76400006109026109238686610d6b565b6109366002670de0b6b3a76400006110ee565b90610d83565b60008061094a6002846110ee565b905061070d8361090261096587670de0b6b3a7640000610d6b565b8490610d83565b60006105218383670de0b6b3a7640000610908610d8f565b60008080838162253d8c61099b8362010bd9611229565b6109a59190611229565b9050600062023ab16109b883600461126a565b6109c291906112ef565b905060046109d38262023ab161126a565b6109de906003611229565b6109e891906112ef565b6109f2908361131d565b9150600062164b09610a05846001611229565b610a1190610fa061126a565b610a1b91906112ef565b90506004610a2b826105b561126a565b610a3591906112ef565b610a3f908461131d565b610a4a90601f611229565b9250600061098f610a5c85605061126a565b610a6691906112ef565b905060006050610a788361098f61126a565b610a8291906112ef565b610a8c908661131d565b9050610a99600b836112ef565b9450610aa685600c61126a565b610ab1836002611229565b610abb919061131d565b91508483610aca60318761131d565b610ad590606461126a565b610adf9190611229565b610ae99190611229565b9a919950975095505050505050565b60008160011480610b095750816003145b80610b145750816005145b80610b1f5750816007145b80610b2a5750816008145b80610b35575081600a145b80610b40575081600c145b15610b4d5750601f610524565b81600214610b5d5750601e610524565b610b6683610e01565b610b7157601c610b74565b601d5b60ff169392505050565b60006107b2841015610b8f57600080fd5b838383600062253d8c60046064600c610ba9600e8861131d565b610bb391906112ef565b610bbf88611324611229565b610bc99190611229565b610bd391906112ef565b610bde90600361126a565b610be891906112ef565b600c80610bf6600e8861131d565b610c0091906112ef565b610c0b90600c61126a565b610c1660028861131d565b610c20919061131d565b610c2c9061016f61126a565b610c3691906112ef565b6004600c610c45600e8961131d565b610c4f91906112ef565b610c5b896112c0611229565b610c659190611229565b610c71906105b561126a565b610c7b91906112ef565b610c87617d4b8761131d565b610c919190611229565b610c9b9190611229565b610ca5919061131d565b610caf919061131d565b98975050505050505050565b600080806000198587098587029250828110838203039150508060001415610cf657838281610cec57610cec6110d8565b0492505050610508565b808411610d0257600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600061052182846110b9565b600061052182846110ee565b60006105218284611011565b6000610d9c600285611125565b610da65782610da8565b845b9050610db56002856110ee565b93505b831561070d57610dcc85868463ffffffff16565b9450610dd9600285611125565b15610def57610dec81868463ffffffff16565b90505b610dfa6002856110ee565b9350610db8565b6000610e0e600483611125565b158015610e245750610e21606483611125565b15155b806105245750610e3661019083611125565b1592915050565b60028110610e4a57600080fd5b50565b803563ffffffff81168114610e6157600080fd5b919050565b60008060008060008060c08789031215610e7f57600080fd5b8635610e8a81610e3d565b95506020870135610e9a81610e3d565b945060408701359350610eaf60608801610e4d565b9250610ebd60808801610e4d565b915060a087013561ffff81168114610ed457600080fd5b809150509295509295509295565b600080600080600060a08688031215610efa57600080fd5b610f0386610e4d565b9450610f1160208701610e4d565b9350610f1f60408701610e4d565b9250610f2d60608701610e4d565b91506080860135610f3d81610e3d565b809150509295509295909350565b600080600080600060a08688031215610f6357600080fd5b8535945060208601359350604086013592506060860135610f8381610e3d565b9150610f9160808701610e4d565b90509295509295909350565b60008060008060808587031215610fb357600080fd5b84359350602085013592506040850135610fcc81610e3d565b9150610fda60608601610e4d565b905092959194509250565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052601160045260246000fd5b6000821982111561102457611024610ffb565b500190565b600063ffffffff80831681851680830382111561104857611048610ffb565b01949350505050565b600063ffffffff8381169083168181101561106e5761106e610ffb565b039392505050565b600063ffffffff8083168185168183048111821515161561109957611099610ffb565b02949350505050565b6000828210156110b4576110b4610ffb565b500390565b60008160001904831182151516156110d3576110d3610ffb565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826110fd576110fd6110d8565b500490565b600063ffffffff80841680611119576111196110d8565b92169190910692915050565b600082611134576111346110d8565b500690565b600181815b8085111561117457816000190482111561115a5761115a610ffb565b8085161561116757918102915b93841c939080029061113e565b509250929050565b60008261118b57506001610524565b8161119857506000610524565b81600181146111ae57600281146111b8576111d4565b6001915050610524565b60ff8411156111c9576111c9610ffb565b50506001821b610524565b5060208310610133831016604e8410600b84101617156111f7575081810a610524565b6112018383611139565b806000190482111561121557611215610ffb565b029392505050565b6000610521838361117c565b600080821280156001600160ff1b038490038513161561124b5761124b610ffb565b600160ff1b839003841281161561126457611264610ffb565b50500190565b60006001600160ff1b038184138284138082168684048611161561129057611290610ffb565b600160ff1b60008712828116878305891216156112af576112af610ffb565b600087129250878205871284841616156112cb576112cb610ffb565b878505871281841616156112e1576112e1610ffb565b505050929093029392505050565b6000826112fe576112fe6110d8565b600160ff1b82146000198414161561131857611318610ffb565b500590565b60008083128015600160ff1b85018412161561133b5761133b610ffb565b6001600160ff1b038401831381161561135657611356610ffb565b5050039056fea26469706673582212201805a8c1fc5dbad11bf668affb239698debc8abd9917c3dc8f4507bfc269ea2164736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": { + "calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)": { + "params": { + "_bid": "The loan bid struct to get the owed amount for.", + "_paymentCycleType": "The payment cycle type of the loan (Seconds or Monthly).", + "_timestamp": "The timestamp at which to get the owed amount at." + } + }, + "calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)": { + "params": { + "_apr": "The annual percentage rate of the loan.", + "_cycleType": "The cycle type set for the loan. (Seconds or Monthly)", + "_duration": "The length of the loan.", + "_paymentCycle": "The length of the loan's payment cycle.", + "_principal": "The starting amount that is owed on the loan.", + "_type": "The payment type of the loan." + } + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": { + "calculateAmountOwed(Bid storage,uint256,PaymentCycleType,uint32)": { + "notice": "Calculates the amount owed for a loan." + }, + "calculatePaymentCycleAmount(PaymentType,PaymentCycleType,uint256,uint32,uint32,uint16)": { + "notice": "Calculates the amount owed for a loan for the next payment cycle." + } + }, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json b/packages/contracts/deployments/apechain/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json new file mode 100644 index 000000000..be5b16311 --- /dev/null +++ b/packages/contracts/deployments/apechain/solcInputs/0734360f150a1a42bdf38edcad8bf3ab.json @@ -0,0 +1,890 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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 bool public liquidationsPaused; \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 \"oSCF\"\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, \"IRL\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"LTP\"); \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, \"PRL\");\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 \"ST\"\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, \"B\" );\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, \"SM\" );\n \n if(!firstDepositMade){\n require(msg.sender == owner(), \"F.\");\n require( sharesAmount_>= 1e6, \"SA\" );\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 \"CT\"\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 \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"BC\"\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 ,\"W\");\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 require(!liquidationsPaused );\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 );\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() external 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 \"Ldt\"\n );\n require(\n block.timestamp > _loanDefaultedTimestamp,\n \"Ldp\"\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\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pauseLiquidations() public virtual onlyProtocolPauser {\n require(!liquidationsPaused);\n liquidationsPaused = true;\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop.\n */\n function unpauseLiquidations() public virtual onlyProtocolPauser {\n\n require(liquidationsPaused);\n\n setLastUnpausedAt();\n liquidationsPaused = false;\n }\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\n// import \"forge-std/console.sol\"; // Not needed for Hardhat deployment\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\n//import \"forge-std/console.sol\";\n \n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\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 diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index 12fcc0730..b3417da99 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -475,7 +475,7 @@ export default { 56: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534', 11155111: '0xFe5394B67196EA95301D6ECB5389E98A02984cC2', 999: '0xBf4E3fEA276057D0b26f52141557C835a7E2d534', - 33139: 0 // apechain - TBD after deployment + 33139: '0x6b1eC259a35005b7562c92f42C490f39131fF1d8' // apechain }, }, From f1e551ed2e2aa1b0d3a17dd0b20045d428c8b2af Mon Sep 17 00:00:00 2001 From: StarkBot Date: Thu, 26 Feb 2026 19:03:41 -0500 Subject: [PATCH 42/46] add tests --- .../tests_fork/ApeChain_DeployPool_Test.sol | 285 +++++++++++ .../ApeChain_PoolLifecycle_Test.sol | 334 ++++++++++++ .../tests_fork/BSC_DeployPool_Test.sol | 224 ++++++++ .../tests_fork/BSC_PoolLifecycle_Test.sol | 483 ++++++++++++++++++ 4 files changed, 1326 insertions(+) create mode 100644 packages/contracts/tests_fork/ApeChain_DeployPool_Test.sol create mode 100644 packages/contracts/tests_fork/ApeChain_PoolLifecycle_Test.sol create mode 100644 packages/contracts/tests_fork/BSC_DeployPool_Test.sol create mode 100644 packages/contracts/tests_fork/BSC_PoolLifecycle_Test.sol diff --git a/packages/contracts/tests_fork/ApeChain_DeployPool_Test.sol b/packages/contracts/tests_fork/ApeChain_DeployPool_Test.sol new file mode 100644 index 000000000..a94ba72ec --- /dev/null +++ b/packages/contracts/tests_fork/ApeChain_DeployPool_Test.sol @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + +import { LenderCommitmentGroupFactory_V2 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol"; +import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommitmentGroup_V2.sol"; +import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; + +interface IERC20 { + function balanceOf(address account) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function symbol() external view returns (string memory); + function decimals() external view returns (uint8); + function transfer(address to, uint256 amount) external returns (bool); +} + +/// @notice Algebra (Camelot V3) factory interface — no fee parameter, uses poolByPair +interface IAlgebraFactory { + function poolByPair(address tokenA, address tokenB) external view returns (address pool); +} + +/// @notice Algebra pool interface — uses globalState() instead of slot0(), getTimepoints() instead of observe() +interface IAlgebraPool { + function token0() external view returns (address); + function token1() external view returns (address); + /// @dev Algebra V1 globalState has 8 return values (not 6 like Algebra Integral) + function globalState() external view returns ( + uint160 price, // sqrt(token1/token0) * 2^96 + int24 tick, // current tick + uint16 feeZto, // fee for zero-to-one swaps + uint16 feeOtz, // fee for one-to-zero swaps + uint16 timepointIndex, // oracle timepoint index + uint8 communityFeeToken0, // community fee for token0 + uint8 communityFeeToken1, // community fee for token1 + bool unlocked // reentrancy lock + ); + function getTimepoints(uint32[] calldata secondsAgos) external view returns ( + int56[] memory tickCumulatives, + uint160[] memory secondsPerLiquidityCumulatives + ); +} + +/// @notice Standard Uniswap V3 pool interface — what Teller's UniswapPricingLibraryV2 expects +interface IUniswapV3Pool { + function slot0() external view returns ( + uint160 sqrtPriceX96, + int24 tick, + uint16 observationIndex, + uint16 observationCardinality, + uint16 observationCardinalityNext, + uint8 feeProtocol, + bool unlocked + ); + function observe(uint32[] calldata secondsAgos) external view returns ( + int56[] memory tickCumulatives, + uint160[] memory secondsPerLiquidityCumulativeX128s + ); + function token0() external view returns (address); + function token1() external view returns (address); +} + +interface IMarketRegistry { + function createMarket( + address _initialOwner, + uint32 _paymentCycleDuration, + uint32 _paymentDefaultDuration, + uint32 _bidExpirationTime, + uint16 _feePercent, + bool _requireLenderAttestation, + bool _requireBorrowerAttestation, + string calldata _uri + ) external returns (uint256 marketId_); +} + +interface ITellerV2 { + function marketRegistry() external view returns (address); + function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; +} + +contract ApeChain_DeployPool_Fork_Test is Test { + + string constant NETWORK_NAME = "apechain"; + + // ApeChain ecosystem addresses + address constant CAMELOT_V3_FACTORY = 0x10aA510d94E094Bd643677bd2964c3EE085Daffc; // Algebra factory + address constant WAPE = 0x48b62137EdfA95a428D35C09E44256a739F6B557; + address constant ApeUSD = 0xA2235d059F80e176D931Ef76b6C51953Eb3fBEf4; + + LenderCommitmentGroupFactory_V2 factoryv2; + ITellerV2 tellerV2; + IMarketRegistry marketRegistry; + address smartCommitmentForwarder; + + uint256 marketId; + + using stdJson for string; + + function getDeployedAddress(string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + function setUp() public { + console.log("Chain ID:", block.chainid); + console.log("Block number:", block.number); + + // Load deployed contracts + address payable factoryAddr = payable(getDeployedAddress("LenderCommitmentGroupFactory_V2")); + factoryv2 = LenderCommitmentGroupFactory_V2(factoryAddr); + assertTrue(factoryAddr.code.length > 0, "Factory contract not found on ApeChain"); + + tellerV2 = ITellerV2(getDeployedAddress("TellerV2")); + smartCommitmentForwarder = getDeployedAddress("SmartCommitmentForwarder"); + marketRegistry = IMarketRegistry(tellerV2.marketRegistry()); + + console.log("Factory:", factoryAddr); + console.log("TellerV2:", address(tellerV2)); + console.log("SmartCommitmentForwarder:", smartCommitmentForwarder); + console.log("MarketRegistry:", address(marketRegistry)); + + // Create a market + address marketOwner = address(this); + marketId = marketRegistry.createMarket( + marketOwner, + 2592000, + 2592000, + 86400, + 0, + false, + false, + "" + ); + console.log("Created market ID:", marketId); + + tellerV2.setTrustedMarketForwarder(marketId, smartCommitmentForwarder); + } + + function test_verifyApeChainDeployments() public { + address collateralManager = getDeployedAddress("CollateralManager"); + assertTrue(address(tellerV2).code.length > 0, "TellerV2 not deployed"); + assertTrue(smartCommitmentForwarder.code.length > 0, "SmartCommitmentForwarder not deployed"); + assertTrue(collateralManager.code.length > 0, "CollateralManager not deployed"); + + // ApeChain also has BorrowSwap (unlike BSC) + address borrowSwap = getDeployedAddress("BorrowSwap"); + assertTrue(borrowSwap.code.length > 0, "BorrowSwap not deployed"); + + console.log("All core contracts verified on ApeChain"); + } + + function test_verifyCamelotV3Pool() public { + IAlgebraFactory factory = IAlgebraFactory(CAMELOT_V3_FACTORY); + + // Camelot V3 (Algebra) uses poolByPair — no fee tiers + address pool = factory.poolByPair(WAPE, ApeUSD); + console.log("WAPE/ApeUSD Camelot V3 pool:", pool); + assertTrue(pool != address(0), "No Camelot V3 WAPE/ApeUSD pool found"); + + // Verify tokens + IAlgebraPool algebraPool = IAlgebraPool(pool); + console.log("token0:", algebraPool.token0()); + console.log("token1:", algebraPool.token1()); + + // globalState() works on Algebra pools + (uint160 price,, uint16 feeZto,, uint16 timepointIndex,,, bool unlocked) = algebraPool.globalState(); + console.log("=== globalState() works (Algebra V1 - 8 return values) ==="); + console.log("sqrtPrice:", price); + console.log("feeZto:", uint256(feeZto)); + console.log("timepointIndex:", uint256(timepointIndex)); + console.log("unlocked:", unlocked); + assertGt(price, 0, "Price should be non-zero"); + + // getTimepoints() works on Algebra pools (same as observe()) + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = 5; + secondsAgos[1] = 0; + (int56[] memory tickCumulatives, ) = algebraPool.getTimepoints(secondsAgos); + console.log("=== getTimepoints() works ==="); + assertTrue(tickCumulatives.length == 2, "Should return 2 tick cumulatives"); + } + + /// @notice This test DEMONSTRATES the incompatibility — slot0() reverts on Camelot V3 + function test_slot0_REVERTS_on_CamelotV3() public { + IAlgebraFactory factory = IAlgebraFactory(CAMELOT_V3_FACTORY); + address pool = factory.poolByPair(WAPE, ApeUSD); + + // slot0() does NOT exist on Algebra pools — this WILL revert + IUniswapV3Pool uniPool = IUniswapV3Pool(pool); + vm.expectRevert(); + uniPool.slot0(); + + console.log("CONFIRMED: slot0() reverts on Camelot V3 (Algebra) pools"); + } + + /// @notice This test DEMONSTRATES the incompatibility — observe() reverts on Camelot V3 + function test_observe_REVERTS_on_CamelotV3() public { + IAlgebraFactory factory = IAlgebraFactory(CAMELOT_V3_FACTORY); + address pool = factory.poolByPair(WAPE, ApeUSD); + + // observe() does NOT exist on Algebra pools — this WILL revert + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = 5; + secondsAgos[1] = 0; + + IUniswapV3Pool uniPool = IUniswapV3Pool(pool); + vm.expectRevert(); + uniPool.observe(secondsAgos); + + console.log("CONFIRMED: observe() reverts on Camelot V3 (Algebra) pools"); + } + + /// @notice Pool deployment succeeds because the factory does NOT call the pricing + /// library during initialization. The oracle is only invoked during borrow/liquidation. + function test_deployPoolV2_on_CamelotV3() public { + IAlgebraFactory factory = IAlgebraFactory(CAMELOT_V3_FACTORY); + address pool = factory.poolByPair(WAPE, ApeUSD); + require(pool != address(0), "No WAPE/ApeUSD pool"); + + IAlgebraPool algebraPool = IAlgebraPool(pool); + address token0 = algebraPool.token0(); + bool zeroForOne = (token0 == ApeUSD); + + uint8 apeUsdDecimals = IERC20(ApeUSD).decimals(); + uint8 wapeDecimals = IERC20(WAPE).decimals(); + + console.log("token0:", token0); + console.log("zeroForOne:", zeroForOne); + console.log("ApeUSD decimals:", apeUsdDecimals, "WAPE decimals:", wapeDecimals); + + // Oracle route config — this points to a Camelot V3 (Algebra) pool + // The pool address is valid, but UniswapPricingLibraryV2 will try to call + // slot0()/observe() on it, which will revert + IUniswapPricingLibrary.PoolRouteConfig[] memory routes = new IUniswapPricingLibrary.PoolRouteConfig[](1); + routes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: pool, + zeroForOne: zeroForOne, + twapInterval: 5, + token0Decimals: algebraPool.token0() == ApeUSD ? apeUsdDecimals : wapeDecimals, + token1Decimals: algebraPool.token1() == ApeUSD ? apeUsdDecimals : wapeDecimals + }); + + ILenderCommitmentGroup_V2.CommitmentGroupConfig memory config = ILenderCommitmentGroup_V2.CommitmentGroupConfig({ + principalTokenAddress: ApeUSD, + collateralTokenAddress: WAPE, + marketId: marketId, + maxLoanDuration: 604800, + interestRateLowerBound: 6000, + interestRateUpperBound: 11000, + liquidityThresholdPercent: 8000, + collateralRatio: 15000 + }); + + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + + // ApeUSD is a yield-bearing rebasing token - deal() can't find its balance slot. + // Transfer from the Camelot pool which holds ApeUSD liquidity. + address apeUsdWhale = pool; // Camelot pool holds ApeUSD + uint256 whaleBalance = IERC20(ApeUSD).balanceOf(apeUsdWhale); + require(whaleBalance >= initialDeposit, "Whale has insufficient ApeUSD"); + vm.prank(apeUsdWhale); + IERC20(ApeUSD).transfer(address(this), initialDeposit); + + IERC20(ApeUSD).approve(address(factoryv2), initialDeposit); + + // Pool deployment SUCCEEDS - the pricing library is NOT called during init. + // The oracle (slot0/observe) is only invoked during borrow (collateral pricing) + // and liquidation operations. + console.log("Deploying pool..."); + address deployedPool = factoryv2.deployLenderCommitmentGroupPool( + initialDeposit, + config, + routes + ); + + assertTrue(deployedPool != address(0), "Pool should be deployed"); + assertTrue(deployedPool.code.length > 0, "Pool should have code"); + console.log("=== PoolV2 deployed at:", deployedPool, "==="); + console.log("NOTE: Pool deploys OK, but borrowing will fail when oracle is invoked"); + } +} diff --git a/packages/contracts/tests_fork/ApeChain_PoolLifecycle_Test.sol b/packages/contracts/tests_fork/ApeChain_PoolLifecycle_Test.sol new file mode 100644 index 000000000..337a1d4ac --- /dev/null +++ b/packages/contracts/tests_fork/ApeChain_PoolLifecycle_Test.sol @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + +import { LenderCommitmentGroupFactory_V2 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol"; +import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommitmentGroup_V2.sol"; +import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; + +/** + * @title ApeChain Pool Lifecycle Fork Test + * @notice Tests PoolV2 on ApeChain. Documents three blockers preventing full operation. + * + * BLOCKERS FOUND: + * 1. ALGEBRA ORACLE: Camelot V3 uses globalState()/getTimepoints() but + * UniswapPricingLibraryV2 calls slot0()/observe() which revert. + * Blocks: borrowing, liquidation. + * + * 2. APEUSD REBASING: ApeUSD is a yield-bearing rebasing token. Pool_V2's deposit() + * has a strict balance check (balanceAfter == balanceBefore + amount) which fails + * because rebasing tokens can have rounding differences on transfer. + * Blocks: lender deposits with ApeUSD as principal. + * + * 3. HYPERNATIVE ORACLE: isApproved() reverts on ApeChain's HypernativeOracle. + * Requires tx.origin == msg.sender (EOA shortcut) for all pool operations. + * Blocks: contract-based interactions (smart wallets, multisigs). + * + * WHAT WORKS: + * - All 26 contracts deployed and verified + * - Market creation + * - Pool deployment (oracle not called during init) + * - Factory initial deposit (bypasses TB check via internal path) + * - Camelot V3 pools: globalState() and getTimepoints() both functional + */ + +interface IERC20_APE { + function balanceOf(address account) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function symbol() external view returns (string memory); + function decimals() external view returns (uint8); + function transfer(address to, uint256 amount) external returns (bool); +} + +interface IAlgebraFactory { + function poolByPair(address tokenA, address tokenB) external view returns (address pool); +} + +interface IAlgebraPool { + function token0() external view returns (address); + function token1() external view returns (address); + function globalState() external view returns ( + uint160 price, int24 tick, uint16 feeZto, uint16 feeOtz, + uint16 timepointIndex, uint8 communityFeeToken0, + uint8 communityFeeToken1, bool unlocked + ); + function getTimepoints(uint32[] calldata secondsAgos) external view returns ( + int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulatives + ); +} + +interface IMarketRegistry_APE { + function createMarket( + address _initialOwner, uint32 _paymentCycleDuration, + uint32 _paymentDefaultDuration, uint32 _bidExpirationTime, + uint16 _feePercent, bool _requireLenderAttestation, + bool _requireBorrowerAttestation, string calldata _uri + ) external returns (uint256 marketId_); +} + +interface ITellerV2_APE { + function marketRegistry() external view returns (address); + function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; + function approveMarketForwarder(uint256 _marketId, address _forwarder) external; + function collateralManager() external view returns (address); +} + +interface ISmartCommitmentForwarder_APE { + function acceptSmartCommitmentWithRecipient( + address _smartCommitmentAddress, uint256 _principalAmount, + uint256 _collateralAmount, uint256 _collateralTokenId, + address _collateralTokenAddress, address _recipient, + uint16 _interestRate, uint32 _loanDuration + ) external returns (uint256 bidId); +} + +interface IPoolV2_APE { + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); + function totalAssets() external view returns (uint256); + function totalSupply() external view returns (uint256); + function balanceOf(address account) external view returns (uint256); + function getPrincipalAmountAvailableToBorrow() external view returns (uint256); + function asset() external view returns (address); + function name() external view returns (string memory); + function symbol() external view returns (string memory); +} + +contract ApeChain_PoolLifecycle_Fork_Test is Test { + + string constant NETWORK_NAME = "apechain"; + + address constant CAMELOT_V3_FACTORY = 0x10aA510d94E094Bd643677bd2964c3EE085Daffc; + address constant WAPE = 0x48b62137EdfA95a428D35C09E44256a739F6B557; + address constant ApeUSD = 0xA2235d059F80e176D931Ef76b6C51953Eb3fBEf4; + + LenderCommitmentGroupFactory_V2 factoryv2; + ITellerV2_APE tellerV2; + IMarketRegistry_APE marketRegistry; + address smartCommitmentForwarder; + address collateralManager; + + uint256 marketId; + + address camelotPool; + bool zeroForOne; + uint8 apeUsdDecimals; + uint8 wapeDecimals; + + address lender = address(0xA001); + address borrower = address(0xB001); + + using stdJson for string; + + function getDeployedAddress(string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + function setUp() public { + address payable factoryAddr = payable(getDeployedAddress("LenderCommitmentGroupFactory_V2")); + factoryv2 = LenderCommitmentGroupFactory_V2(factoryAddr); + assertTrue(factoryAddr.code.length > 0, "Factory not found"); + + tellerV2 = ITellerV2_APE(getDeployedAddress("TellerV2")); + smartCommitmentForwarder = getDeployedAddress("SmartCommitmentForwarder"); + marketRegistry = IMarketRegistry_APE(tellerV2.marketRegistry()); + collateralManager = tellerV2.collateralManager(); + + marketId = marketRegistry.createMarket( + address(this), 2592000, 2592000, 86400, 0, false, false, "" + ); + tellerV2.setTrustedMarketForwarder(marketId, smartCommitmentForwarder); + + camelotPool = IAlgebraFactory(CAMELOT_V3_FACTORY).poolByPair(WAPE, ApeUSD); + require(camelotPool != address(0), "No WAPE/ApeUSD Camelot pool"); + + IAlgebraPool pool = IAlgebraPool(camelotPool); + zeroForOne = (pool.token0() == ApeUSD); + apeUsdDecimals = IERC20_APE(ApeUSD).decimals(); + wapeDecimals = IERC20_APE(WAPE).decimals(); + } + + // ============ Helpers ============ + + function _getApeUSD(address to, uint256 amount) internal { + vm.prank(camelotPool); + IERC20_APE(ApeUSD).transfer(to, amount); + } + + function _buildOracleRoutes() internal view returns (IUniswapPricingLibrary.PoolRouteConfig[] memory) { + IAlgebraPool pool = IAlgebraPool(camelotPool); + IUniswapPricingLibrary.PoolRouteConfig[] memory routes = new IUniswapPricingLibrary.PoolRouteConfig[](1); + routes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: camelotPool, + zeroForOne: zeroForOne, + twapInterval: 5, + token0Decimals: pool.token0() == ApeUSD ? apeUsdDecimals : wapeDecimals, + token1Decimals: pool.token1() == ApeUSD ? apeUsdDecimals : wapeDecimals + }); + return routes; + } + + function _deployPool(uint256 initialDeposit) internal returns (address) { + ILenderCommitmentGroup_V2.CommitmentGroupConfig memory config = ILenderCommitmentGroup_V2.CommitmentGroupConfig({ + principalTokenAddress: ApeUSD, + collateralTokenAddress: WAPE, + marketId: marketId, + maxLoanDuration: 604800, + interestRateLowerBound: 6000, + interestRateUpperBound: 11000, + liquidityThresholdPercent: 8000, + collateralRatio: 15000 + }); + + _getApeUSD(address(this), initialDeposit); + IERC20_APE(ApeUSD).approve(address(factoryv2), initialDeposit); + + return factoryv2.deployLenderCommitmentGroupPool( + initialDeposit, config, _buildOracleRoutes() + ); + } + + // ============ Compatibility diagnostics ============ + + function test_algebraGlobalState_works() public { + IAlgebraPool pool = IAlgebraPool(camelotPool); + (uint160 price,,,,,,, bool unlocked) = pool.globalState(); + assertGt(price, 0, "Price should be non-zero"); + assertTrue(unlocked, "Pool should be unlocked"); + console.log("globalState sqrtPrice:", price); + } + + function test_algebraGetTimepoints_works() public { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = 6; + secondsAgos[1] = 1; + IAlgebraPool pool = IAlgebraPool(camelotPool); + (int56[] memory tickCumulatives,) = pool.getTimepoints(secondsAgos); + assertTrue(tickCumulatives.length == 2, "Should return 2 tick cumulatives"); + console.log("getTimepoints() returned valid TWAP data"); + } + + function test_slot0_reverts() public { + (bool success,) = camelotPool.staticcall(abi.encodeWithSignature("slot0()")); + assertFalse(success, "slot0() should revert on Algebra pool"); + console.log("CONFIRMED: slot0() reverts on Camelot V3"); + } + + function test_observe_reverts() public { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = 5; + secondsAgos[1] = 0; + (bool success,) = camelotPool.staticcall( + abi.encodeWithSignature("observe(uint32[])", secondsAgos) + ); + assertFalse(success, "observe() should revert on Algebra pool"); + console.log("CONFIRMED: observe() reverts on Camelot V3"); + } + + // ============ Lifecycle Tests ============ + + /// @notice Pool deployment succeeds (oracle not called during init) + function test_poolDeployment_succeeds() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPool(initialDeposit); + + assertTrue(pool != address(0), "Pool should be deployed"); + assertTrue(pool.code.length > 0, "Pool should have code"); + + // Factory initial deposit works because it goes through an internal path + // that doesn't have the strict TB balance check + console.log("Pool deployed:", pool); + console.log("Pool name:", IPoolV2_APE(pool).name()); + console.log("Pool totalAssets:", IPoolV2_APE(pool).totalAssets()); + console.log("Initial shares:", IPoolV2_APE(pool).totalSupply()); + } + + /// @notice BLOCKER #2: Lender deposit fails because ApeUSD is rebasing. + /// Pool_V2 deposit() checks: balanceAfter == balanceBefore + amount ("TB") + /// Rebasing tokens have rounding on transfer, so this strict check fails. + function test_lenderDeposit_FAILS_rebasingToken() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPool(initialDeposit); + + uint256 depositAmount = 500 * 10**apeUsdDecimals; + _getApeUSD(lender, depositAmount); + + vm.startPrank(lender, lender); + IERC20_APE(ApeUSD).approve(pool, depositAmount); + + // Reverts with "TB" (Token Balance) because ApeUSD is rebasing: + // balanceAfter != balanceBefore + amount due to share/balance rounding + vm.expectRevert(bytes("TB")); + IPoolV2_APE(pool).deposit(depositAmount, lender); + vm.stopPrank(); + + console.log("CONFIRMED: Lender deposit fails with ApeUSD (rebasing token)"); + console.log("Pool_V2 deposit() has strict balance check incompatible with rebasing"); + } + + /// @notice BLOCKER #1: Borrowing would fail because observe() reverts on Algebra. + /// The oracle is called during acceptFundsForAcceptBid -> collateral pricing. + /// This is proven by test_observe_reverts() and test_slot0_reverts() above. + /// We don't execute the full borrow flow here because deal(WAPE) has issues + /// on the Tenderly fork, but the root cause is confirmed: + /// acceptFundsForAcceptBid -> calculateCollateralTokensAmountEquivalentToPrincipalTokens + /// -> UniswapPricingLibraryV2.getSqrtTwapX96() -> observe() -> REVERT + function test_borrow_BLOCKED_oracleIncompat() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPool(initialDeposit); + + // Verify pool has liquidity but oracle would fail + uint256 available = IPoolV2_APE(pool).getPrincipalAmountAvailableToBorrow(); + console.log("Available to borrow:", available); + assertGt(available, 0, "Pool has liquidity"); + + // But borrowing is impossible because observe() reverts on Algebra pools + // (proven by test_observe_reverts and test_slot0_reverts) + console.log("BLOCKED: Borrowing impossible - observe() reverts on Camelot V3"); + } + + /// @notice Summary of all findings + function test_fullLifecycleStatus() public { + console.log("=== ApeChain PoolV2 Lifecycle Report ==="); + console.log(""); + console.log("Implementation: LenderCommitmentGroup_Pool_V2 (ERC4626)"); + console.log("DEX: Camelot V3 (Algebra V1)"); + console.log("Principal: ApeUSD (rebasing yield token)"); + console.log("Collateral: WAPE"); + console.log(""); + console.log("BLOCKER #1 - Algebra Oracle Incompatibility:"); + console.log(" observe()/slot0() don't exist on Camelot V3"); + console.log(" Need: globalState() + getTimepoints() adapter"); + console.log(" Blocks: borrowing, liquidation"); + console.log(""); + console.log("BLOCKER #2 - ApeUSD Rebasing Token:"); + console.log(" deposit() strict balance check fails (TB error)"); + console.log(" balanceAfter != balanceBefore + amount due to rounding"); + console.log(" Blocks: all lender deposits after factory init"); + console.log(""); + console.log("BLOCKER #3 - HypernativeOracle:"); + console.log(" isApproved() reverts, EOA shortcut required"); + console.log(" Blocks: smart wallet / multisig interactions"); + console.log(""); + console.log("WHAT WORKS:"); + console.log(" - 26 contracts deployed and verified"); + console.log(" - Market creation"); + console.log(" - Pool deployment with factory initial deposit"); + console.log(" - Camelot V3 globalState() and getTimepoints()"); + + // Verify + assertTrue(address(factoryv2).code.length > 0); + assertTrue(address(tellerV2).code.length > 0); + assertTrue(camelotPool != address(0)); + + IAlgebraPool pool = IAlgebraPool(camelotPool); + (uint160 price,,,,,,, ) = pool.globalState(); + assertGt(price, 0, "Algebra pool has valid price data"); + } +} diff --git a/packages/contracts/tests_fork/BSC_DeployPool_Test.sol b/packages/contracts/tests_fork/BSC_DeployPool_Test.sol new file mode 100644 index 000000000..ab993a066 --- /dev/null +++ b/packages/contracts/tests_fork/BSC_DeployPool_Test.sol @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + +import { LenderCommitmentGroupFactory_V2 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol"; +import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommitmentGroup_V2.sol"; +import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; + +interface IERC20 { + function balanceOf(address account) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function symbol() external view returns (string memory); + function decimals() external view returns (uint8); + function transfer(address to, uint256 amount) external returns (bool); +} + +interface IUniswapV3Pool { + function token0() external view returns (address); + function token1() external view returns (address); + function fee() external view returns (uint24); + function slot0() external view returns ( + uint160 sqrtPriceX96, + int24 tick, + uint16 observationIndex, + uint16 observationCardinality, + uint16 observationCardinalityNext, + uint8 feeProtocol, + bool unlocked + ); +} + +interface IUniswapV3Factory { + function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool); +} + +interface IMarketRegistry { + function getMarketOwner(uint256 marketId) external view returns (address); + function createMarket( + address _initialOwner, + uint32 _paymentCycleDuration, + uint32 _paymentDefaultDuration, + uint32 _bidExpirationTime, + uint16 _feePercent, + bool _requireLenderAttestation, + bool _requireBorrowerAttestation, + string calldata _uri + ) external returns (uint256 marketId_); +} + +interface ITellerV2 { + function marketRegistry() external view returns (address); + function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; + function approveMarketForwarder(uint256 _marketId, address _forwarder) external; +} + +contract BSC_DeployPool_Fork_Test is Test { + + string constant NETWORK_NAME = "bsc"; + + // BSC ecosystem addresses + address constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865; + address constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; + address constant USDT = 0x55d398326f99059fF775485246999027B3197955; // BSC-USD (USDT) + + LenderCommitmentGroupFactory_V2 factoryv2; + ITellerV2 tellerV2; + IMarketRegistry marketRegistry; + address smartCommitmentForwarder; + + uint256 marketId; + + using stdJson for string; + + function getDeployedAddress(string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + function setUp() public { + console.log("Chain ID:", block.chainid); + console.log("Block number:", block.number); + + // Verify we're on BSC fork + assertEq(block.chainid, 56, "Should be on BSC (chain 56)"); + + address payable factoryAddr = payable(getDeployedAddress("LenderCommitmentGroupFactory_V2")); + factoryv2 = LenderCommitmentGroupFactory_V2(factoryAddr); + assertTrue(factoryAddr.code.length > 0, "Factory contract not found on BSC"); + + tellerV2 = ITellerV2(getDeployedAddress("TellerV2")); + smartCommitmentForwarder = getDeployedAddress("SmartCommitmentForwarder"); + marketRegistry = IMarketRegistry(tellerV2.marketRegistry()); + + console.log("Factory:", factoryAddr); + console.log("TellerV2:", address(tellerV2)); + console.log("SmartCommitmentForwarder:", smartCommitmentForwarder); + console.log("MarketRegistry:", address(marketRegistry)); + + // Create a market on BSC (no markets exist yet) + address marketOwner = address(this); + marketId = marketRegistry.createMarket( + marketOwner, + 2592000, // 30 day payment cycle + 2592000, // 30 day default duration + 86400, // 1 day bid expiration + 0, // 0% market fee + false, // no lender attestation + false, // no borrower attestation + "" + ); + console.log("Created market ID:", marketId); + + // Set SmartCommitmentForwarder as trusted forwarder for this market + tellerV2.setTrustedMarketForwarder(marketId, smartCommitmentForwarder); + console.log("Set trusted market forwarder"); + } + + function test_verifyBSCDeployments() public { + address collateralManager = getDeployedAddress("CollateralManager"); + assertTrue(address(tellerV2).code.length > 0, "TellerV2 not deployed"); + assertTrue(smartCommitmentForwarder.code.length > 0, "SmartCommitmentForwarder not deployed"); + assertTrue(collateralManager.code.length > 0, "CollateralManager not deployed"); + console.log("All core contracts verified on BSC"); + } + + function test_verifyPancakeSwapPool() public { + IUniswapV3Factory factory = IUniswapV3Factory(PANCAKE_V3_FACTORY); + + address pool500 = factory.getPool(USDT, WBNB, 500); + address pool2500 = factory.getPool(USDT, WBNB, 2500); + address pool10000 = factory.getPool(USDT, WBNB, 10000); + + console.log("USDT/WBNB pool (0.05%):", pool500); + console.log("USDT/WBNB pool (0.25%):", pool2500); + console.log("USDT/WBNB pool (1%):", pool10000); + + bool hasPool = pool500 != address(0) || pool2500 != address(0) || pool10000 != address(0); + assertTrue(hasPool, "No PancakeSwap V3 USDT/WBNB pool found"); + } + + function test_deployPoolV2() public { + // Find a valid PancakeSwap V3 pool for USDT/WBNB oracle route + IUniswapV3Factory pancakeFactory = IUniswapV3Factory(PANCAKE_V3_FACTORY); + + address uniPool; + uint24[] memory fees = new uint24[](3); + fees[0] = 500; + fees[1] = 2500; + fees[2] = 10000; + + for (uint i = 0; i < fees.length; i++) { + address candidate = pancakeFactory.getPool(USDT, WBNB, fees[i]); + if (candidate != address(0) && candidate.code.length > 0) { + uniPool = candidate; + console.log("Using PancakeSwap pool:", candidate, "fee:", fees[i]); + break; + } + } + require(uniPool != address(0), "No USDT/WBNB pool found on PancakeSwap V3"); + + // Determine token ordering + IUniswapV3Pool pool = IUniswapV3Pool(uniPool); + address token0 = pool.token0(); + address token1 = pool.token1(); + bool zeroForOne = (token0 == USDT); + + uint8 usdtDecimals = IERC20(USDT).decimals(); + uint8 wbnbDecimals = IERC20(WBNB).decimals(); + + console.log("token0:", token0, "token1:", token1); + console.log("zeroForOne:", zeroForOne); + console.log("USDT decimals:", usdtDecimals, "WBNB decimals:", wbnbDecimals); + + // Oracle route: single hop USDT <-> WBNB + IUniswapPricingLibrary.PoolRouteConfig[] memory routes = new IUniswapPricingLibrary.PoolRouteConfig[](1); + routes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: uniPool, + zeroForOne: zeroForOne, + twapInterval: 5, + token0Decimals: pool.token0() == USDT ? usdtDecimals : wbnbDecimals, + token1Decimals: pool.token1() == USDT ? usdtDecimals : wbnbDecimals + }); + + // Pool config: USDT principal, WBNB collateral + ILenderCommitmentGroup_V2.CommitmentGroupConfig memory config = ILenderCommitmentGroup_V2.CommitmentGroupConfig({ + principalTokenAddress: USDT, + collateralTokenAddress: WBNB, + marketId: marketId, + maxLoanDuration: 604800, // 1 week + interestRateLowerBound: 6000, // 60% + interestRateUpperBound: 11000, // 110% + liquidityThresholdPercent: 8000, // 80% + collateralRatio: 15000 // 150% + }); + + // Fund with USDT + uint256 initialDeposit = 100 * 10**usdtDecimals; // 100 USDT + deal(USDT, address(this), initialDeposit); + + console.log("USDT balance:", IERC20(USDT).balanceOf(address(this))); + + // Approve factory + IERC20(USDT).approve(address(factoryv2), initialDeposit); + + // Deploy the pool! + address deployedPool = factoryv2.deployLenderCommitmentGroupPool( + initialDeposit, + config, + routes + ); + + console.log("=== PoolV2 deployed at:", deployedPool, "==="); + assertTrue(deployedPool != address(0), "Pool should be deployed"); + assertTrue(deployedPool.code.length > 0, "Deployed pool should have code"); + + // Verify we can read pool state + console.log("Pool deployment and verification successful!"); + } +} diff --git a/packages/contracts/tests_fork/BSC_PoolLifecycle_Test.sol b/packages/contracts/tests_fork/BSC_PoolLifecycle_Test.sol new file mode 100644 index 000000000..aa3fb35a3 --- /dev/null +++ b/packages/contracts/tests_fork/BSC_PoolLifecycle_Test.sol @@ -0,0 +1,483 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + +import { LenderCommitmentGroupFactory_V2 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V2.sol"; +import { ILenderCommitmentGroup_V2 } from "../contracts/interfaces/ILenderCommitmentGroup_V2.sol"; +import { IUniswapPricingLibrary } from "../contracts/interfaces/IUniswapPricingLibrary.sol"; + +interface IERC20_Lifecycle { + function balanceOf(address account) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function symbol() external view returns (string memory); + function decimals() external view returns (uint8); + function transfer(address to, uint256 amount) external returns (bool); + function allowance(address owner, address spender) external view returns (uint256); +} + +interface IUniswapV3Pool_Lifecycle { + function token0() external view returns (address); + function token1() external view returns (address); + function fee() external view returns (uint24); +} + +interface IUniswapV3Factory_Lifecycle { + function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool); +} + +interface IMarketRegistry_Lifecycle { + function createMarket( + address _initialOwner, + uint32 _paymentCycleDuration, + uint32 _paymentDefaultDuration, + uint32 _bidExpirationTime, + uint16 _feePercent, + bool _requireLenderAttestation, + bool _requireBorrowerAttestation, + string calldata _uri + ) external returns (uint256 marketId_); +} + +interface ITellerV2_Lifecycle { + function marketRegistry() external view returns (address); + function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; + function approveMarketForwarder(uint256 _marketId, address _forwarder) external; + function repayLoanFull(uint256 _bidId) external; + function getBidState(uint256 _bidId) external view returns (uint8); + function collateralManager() external view returns (address); +} + +interface ISmartCommitmentForwarder_Lifecycle { + function acceptSmartCommitmentWithRecipient( + address _smartCommitmentAddress, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration + ) external returns (uint256 bidId); +} + +interface IPoolV2 { + function addPrincipalToCommitmentGroup( + uint256 _amount, + address _sharesRecipient, + uint256 _minSharesAmountOut + ) external returns (uint256 sharesAmount_); + + function prepareSharesForBurn( + uint256 _amountPoolSharesTokens + ) external returns (bool); + + function burnSharesToWithdrawEarnings( + uint256 _amountPoolSharesTokens, + address _recipient, + uint256 _minAmountOut + ) external returns (uint256); + + function poolSharesToken() external view returns (address); + function getPrincipalAmountAvailableToBorrow() external view returns (uint256); + function getCollateralTokenType() external view returns (uint8); + function getMarketId() external view returns (uint256); + function getPrincipalTokenAddress() external view returns (address); + function getCollateralTokenAddress() external view returns (address); +} + +interface ISharesToken { + function balanceOf(address account) external view returns (uint256); + function totalSupply() external view returns (uint256); +} + +contract BSC_PoolLifecycle_Fork_Test is Test { + + string constant NETWORK_NAME = "bsc"; + + // BSC ecosystem addresses + address constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865; + address constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; + address constant USDT = 0x55d398326f99059fF775485246999027B3197955; // BSC-USD (USDT) + + LenderCommitmentGroupFactory_V2 factoryv2; + ITellerV2_Lifecycle tellerV2; + IMarketRegistry_Lifecycle marketRegistry; + address smartCommitmentForwarder; + address collateralManager; + + uint256 marketId; + + // Test actors + address lender = address(0xA001); + address lender2 = address(0xA002); + address borrower = address(0xB001); + + // Shared oracle route config (set in setUp) + address uniPool; + bool zeroForOne; + uint8 usdtDecimals; + uint8 wbnbDecimals; + + using stdJson for string; + + function getDeployedAddress(string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + function setUp() public { + // Verify we're on BSC fork + assertEq(block.chainid, 56, "Should be on BSC (chain 56)"); + + // Load deployed contracts + address payable factoryAddr = payable(getDeployedAddress("LenderCommitmentGroupFactory_V2")); + factoryv2 = LenderCommitmentGroupFactory_V2(factoryAddr); + assertTrue(factoryAddr.code.length > 0, "Factory contract not found on BSC"); + + tellerV2 = ITellerV2_Lifecycle(getDeployedAddress("TellerV2")); + smartCommitmentForwarder = getDeployedAddress("SmartCommitmentForwarder"); + marketRegistry = IMarketRegistry_Lifecycle(tellerV2.marketRegistry()); + collateralManager = tellerV2.collateralManager(); + + console.log("Factory:", factoryAddr); + console.log("TellerV2:", address(tellerV2)); + console.log("SmartCommitmentForwarder:", smartCommitmentForwarder); + console.log("CollateralManager:", collateralManager); + + // Create a market + address marketOwner = address(this); + marketId = marketRegistry.createMarket( + marketOwner, + 2592000, // 30 day payment cycle + 2592000, // 30 day default duration + 86400, // 1 day bid expiration + 0, // 0% market fee + false, // no lender attestation + false, // no borrower attestation + "" + ); + console.log("Created market ID:", marketId); + + // Set SmartCommitmentForwarder as trusted forwarder + tellerV2.setTrustedMarketForwarder(marketId, smartCommitmentForwarder); + + // Find PancakeSwap V3 USDT/WBNB pool + IUniswapV3Factory_Lifecycle pancakeFactory = IUniswapV3Factory_Lifecycle(PANCAKE_V3_FACTORY); + uint24[] memory fees = new uint24[](3); + fees[0] = 500; + fees[1] = 2500; + fees[2] = 10000; + + for (uint i = 0; i < fees.length; i++) { + address candidate = pancakeFactory.getPool(USDT, WBNB, fees[i]); + if (candidate != address(0) && candidate.code.length > 0) { + uniPool = candidate; + console.log("Using PancakeSwap pool:", candidate, "fee:", fees[i]); + break; + } + } + require(uniPool != address(0), "No USDT/WBNB pool found on PancakeSwap V3"); + + // Determine token ordering + IUniswapV3Pool_Lifecycle pool = IUniswapV3Pool_Lifecycle(uniPool); + zeroForOne = (pool.token0() == USDT); + usdtDecimals = IERC20_Lifecycle(USDT).decimals(); + wbnbDecimals = IERC20_Lifecycle(WBNB).decimals(); + } + + // ============ Helpers ============ + + function _buildOracleRoutes() internal view returns (IUniswapPricingLibrary.PoolRouteConfig[] memory) { + IUniswapV3Pool_Lifecycle pool = IUniswapV3Pool_Lifecycle(uniPool); + IUniswapPricingLibrary.PoolRouteConfig[] memory routes = new IUniswapPricingLibrary.PoolRouteConfig[](1); + routes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: uniPool, + zeroForOne: zeroForOne, + twapInterval: 5, + token0Decimals: pool.token0() == USDT ? usdtDecimals : wbnbDecimals, + token1Decimals: pool.token1() == USDT ? usdtDecimals : wbnbDecimals + }); + return routes; + } + + function _deployPool(uint256 initialDeposit) internal returns (address) { + ILenderCommitmentGroup_V2.CommitmentGroupConfig memory config = ILenderCommitmentGroup_V2.CommitmentGroupConfig({ + principalTokenAddress: USDT, + collateralTokenAddress: WBNB, + marketId: marketId, + maxLoanDuration: 604800, // 1 week + interestRateLowerBound: 6000, // 60% + interestRateUpperBound: 11000, // 110% + liquidityThresholdPercent: 8000, // 80% + collateralRatio: 15000 // 150% + }); + + deal(USDT, address(this), initialDeposit); + IERC20_Lifecycle(USDT).approve(address(factoryv2), initialDeposit); + + address deployedPool = factoryv2.deployLenderCommitmentGroupPool( + initialDeposit, + config, + _buildOracleRoutes() + ); + + console.log("Pool deployed at:", deployedPool); + return deployedPool; + } + + function _lenderDeposit(address _lender, address _pool, uint256 _amount) internal returns (uint256 shares) { + deal(USDT, _lender, _amount); + + vm.startPrank(_lender); + IERC20_Lifecycle(USDT).approve(_pool, _amount); + shares = IPoolV2(_pool).addPrincipalToCommitmentGroup(_amount, _lender, 0); + vm.stopPrank(); + + console.log("Lender deposited:", _amount, "shares:", shares); + } + + function _borrowFromPool( + address _borrowerAddr, + address _pool, + uint256 _principalAmount, + uint256 _collateralAmount + ) internal returns (uint256 bidId) { + // Deal collateral (WBNB) to borrower + deal(WBNB, _borrowerAddr, _collateralAmount); + + vm.startPrank(_borrowerAddr); + + // Approve collateral to CollateralManager + IERC20_Lifecycle(WBNB).approve(collateralManager, _collateralAmount); + + // Approve market forwarder for borrower + tellerV2.approveMarketForwarder(marketId, smartCommitmentForwarder); + + // Borrow via SmartCommitmentForwarder + bidId = ISmartCommitmentForwarder_Lifecycle(smartCommitmentForwarder) + .acceptSmartCommitmentWithRecipient( + _pool, + _principalAmount, + _collateralAmount, + 0, // tokenId (0 for ERC20) + WBNB, + _borrowerAddr, + 8000, // 80% interest rate (within bounds 60%-110%) + 604800 // 1 week duration + ); + + vm.stopPrank(); + + console.log("Borrower got bid ID:", bidId); + } + + // ============ Tests ============ + + function test_lenderDeposit() public { + uint256 initialDeposit = 100 * 10**usdtDecimals; + address pool = _deployPool(initialDeposit); + + uint256 depositAmount = 500 * 10**usdtDecimals; + uint256 shares = _lenderDeposit(lender, pool, depositAmount); + + // Verify lender received shares + address sharesToken = IPoolV2(pool).poolSharesToken(); + uint256 lenderShares = ISharesToken(sharesToken).balanceOf(lender); + assertGt(lenderShares, 0, "Lender should have shares"); + assertEq(lenderShares, shares, "Shares should match return value"); + + // Verify pool received USDT + uint256 poolBalance = IERC20_Lifecycle(USDT).balanceOf(pool); + assertGe(poolBalance, depositAmount, "Pool should have at least the deposit amount"); + + console.log("Lender shares:", lenderShares); + console.log("Pool USDT balance:", poolBalance); + } + + function test_borrowFromPool() public { + uint256 initialDeposit = 100 * 10**usdtDecimals; + address pool = _deployPool(initialDeposit); + + // Lender deposits 500 USDT + uint256 lenderAmount = 500 * 10**usdtDecimals; + _lenderDeposit(lender, pool, lenderAmount); + + // Borrower borrows 50 USDT with ~1.3 WBNB collateral (150% ratio) + uint256 borrowAmount = 50 * 10**usdtDecimals; + uint256 collateralAmount = 13 * 10**(wbnbDecimals - 1); // 1.3 WBNB + + uint256 borrowerUsdtBefore = IERC20_Lifecycle(USDT).balanceOf(borrower); + uint256 bidId = _borrowFromPool(borrower, pool, borrowAmount, collateralAmount); + + // Verify borrower received USDT + uint256 borrowerUsdtAfter = IERC20_Lifecycle(USDT).balanceOf(borrower); + assertGe(borrowerUsdtAfter - borrowerUsdtBefore, borrowAmount, "Borrower should have received USDT"); + + // Verify loan is active (state 4 = ACCEPTED in the enum, but let's just check it's non-zero) + console.log("Bid state:", tellerV2.getBidState(bidId)); + console.log("Borrower USDT received:", borrowerUsdtAfter - borrowerUsdtBefore); + } + + function test_repayLoan() public { + uint256 initialDeposit = 100 * 10**usdtDecimals; + address pool = _deployPool(initialDeposit); + + // Lender deposits + uint256 lenderAmount = 500 * 10**usdtDecimals; + _lenderDeposit(lender, pool, lenderAmount); + + // Borrower borrows + uint256 borrowAmount = 50 * 10**usdtDecimals; + uint256 collateralAmount = 13 * 10**(wbnbDecimals - 1); + uint256 bidId = _borrowFromPool(borrower, pool, borrowAmount, collateralAmount); + + // Warp 1 day to accrue some interest + vm.warp(block.timestamp + 1 days); + + // Deal extra USDT to borrower for interest repayment + uint256 repayBuffer = 10 * 10**usdtDecimals; // extra for interest + deal(USDT, borrower, borrowAmount + repayBuffer); + + uint256 borrowerWbnbBefore = IERC20_Lifecycle(WBNB).balanceOf(borrower); + + vm.startPrank(borrower); + IERC20_Lifecycle(USDT).approve(address(tellerV2), borrowAmount + repayBuffer); + tellerV2.repayLoanFull(bidId); + vm.stopPrank(); + + // Verify collateral returned + uint256 borrowerWbnbAfter = IERC20_Lifecycle(WBNB).balanceOf(borrower); + assertGt(borrowerWbnbAfter, borrowerWbnbBefore, "Borrower should have collateral returned"); + console.log("Collateral returned:", borrowerWbnbAfter - borrowerWbnbBefore); + + // Verify loan state changed (no longer ACCEPTED) + console.log("Bid state after repay:", tellerV2.getBidState(bidId)); + } + + function test_lenderWithdraw() public { + uint256 initialDeposit = 100 * 10**usdtDecimals; + address pool = _deployPool(initialDeposit); + + // Lender deposits + uint256 lenderAmount = 500 * 10**usdtDecimals; + uint256 shares = _lenderDeposit(lender, pool, lenderAmount); + + // Borrower borrows, repays with interest + uint256 borrowAmount = 50 * 10**usdtDecimals; + uint256 collateralAmount = 13 * 10**(wbnbDecimals - 1); + uint256 bidId = _borrowFromPool(borrower, pool, borrowAmount, collateralAmount); + + vm.warp(block.timestamp + 1 days); + + uint256 repayBuffer = 10 * 10**usdtDecimals; + deal(USDT, borrower, borrowAmount + repayBuffer); + + vm.startPrank(borrower); + IERC20_Lifecycle(USDT).approve(address(tellerV2), borrowAmount + repayBuffer); + tellerV2.repayLoanFull(bidId); + vm.stopPrank(); + + // Lender prepares shares for withdrawal + vm.startPrank(lender); + IPoolV2(pool).prepareSharesForBurn(shares); + vm.stopPrank(); + + // Warp past withdrawal delay (300s default + buffer) + vm.warp(block.timestamp + 301); + + // Lender withdraws + uint256 lenderUsdtBefore = IERC20_Lifecycle(USDT).balanceOf(lender); + + vm.startPrank(lender); + uint256 withdrawn = IPoolV2(pool).burnSharesToWithdrawEarnings(shares, lender, 0); + vm.stopPrank(); + + uint256 lenderUsdtAfter = IERC20_Lifecycle(USDT).balanceOf(lender); + assertGt(lenderUsdtAfter, lenderUsdtBefore, "Lender should have received USDT"); + assertEq(lenderUsdtAfter - lenderUsdtBefore, withdrawn, "Withdrawn amount should match"); + + console.log("Lender deposited:", lenderAmount); + console.log("Lender withdrawn:", withdrawn); + + // Lender should get back at least their deposit (interest may be shared with initial depositor) + // The initial depositor (factory/test contract) also has shares, so lender gets proportional share + } + + function test_fullLifecycle() public { + uint256 initialDeposit = 100 * 10**usdtDecimals; + address pool = _deployPool(initialDeposit); + + console.log("=== Step 1: Lenders deposit ==="); + + // Lender 1 deposits 500 USDT + uint256 lender1Amount = 500 * 10**usdtDecimals; + uint256 lender1Shares = _lenderDeposit(lender, pool, lender1Amount); + + // Lender 2 deposits 300 USDT + uint256 lender2Amount = 300 * 10**usdtDecimals; + uint256 lender2Shares = _lenderDeposit(lender2, pool, lender2Amount); + + uint256 availableToBorrow = IPoolV2(pool).getPrincipalAmountAvailableToBorrow(); + console.log("Available to borrow:", availableToBorrow); + + console.log("=== Step 2: Borrower borrows ==="); + + uint256 borrowAmount = 100 * 10**usdtDecimals; + uint256 collateralAmount = 13 * 10**(wbnbDecimals - 1) * 2; // ~2.6 WBNB for 100 USDT + uint256 bidId = _borrowFromPool(borrower, pool, borrowAmount, collateralAmount); + + uint256 borrowerUsdt = IERC20_Lifecycle(USDT).balanceOf(borrower); + console.log("Borrower received USDT:", borrowerUsdt); + + console.log("=== Step 3: Time passes, borrower repays ==="); + + // Warp 3 days to accrue interest + vm.warp(block.timestamp + 3 days); + + uint256 repayBuffer = 20 * 10**usdtDecimals; + deal(USDT, borrower, borrowAmount + repayBuffer); + + vm.startPrank(borrower); + IERC20_Lifecycle(USDT).approve(address(tellerV2), borrowAmount + repayBuffer); + tellerV2.repayLoanFull(bidId); + vm.stopPrank(); + + console.log("Loan repaid. Bid state:", tellerV2.getBidState(bidId)); + + console.log("=== Step 4: Lenders withdraw ==="); + + // Lender 1 prepares and withdraws + vm.prank(lender); + IPoolV2(pool).prepareSharesForBurn(lender1Shares); + + // Lender 2 prepares and withdraws + vm.prank(lender2); + IPoolV2(pool).prepareSharesForBurn(lender2Shares); + + // Warp past withdrawal delay + vm.warp(block.timestamp + 301); + + uint256 lender1Before = IERC20_Lifecycle(USDT).balanceOf(lender); + vm.prank(lender); + uint256 lender1Withdrawn = IPoolV2(pool).burnSharesToWithdrawEarnings(lender1Shares, lender, 0); + + uint256 lender2Before = IERC20_Lifecycle(USDT).balanceOf(lender2); + vm.prank(lender2); + uint256 lender2Withdrawn = IPoolV2(pool).burnSharesToWithdrawEarnings(lender2Shares, lender2, 0); + + console.log("Lender1 deposited:", lender1Amount, "withdrawn:", lender1Withdrawn); + console.log("Lender2 deposited:", lender2Amount, "withdrawn:", lender2Withdrawn); + + // Both lenders should receive at least their deposits back (interest earned from loan) + // Note: exact amounts depend on share of pool vs initial depositor + assertGt(lender1Withdrawn, 0, "Lender1 should have withdrawn"); + assertGt(lender2Withdrawn, 0, "Lender2 should have withdrawn"); + + console.log("=== Full lifecycle complete! ==="); + } +} From f5de61b077cd62f8bad653ceee41fe343c89c182 Mon Sep 17 00:00:00 2001 From: Ethereumdegen Date: Thu, 26 Feb 2026 21:41:19 -0500 Subject: [PATCH 43/46] tests --- .../interfaces/defi/IAlgebraPool.sol | 29 + .../contracts/mock/MockPriceAdapter.sol | 24 + .../price_adapters/PriceAdapterAlgebra.sol | 152 ++ .../lender_commitment_group_v3_beacon.ts | 2 +- .../lender_groups_factory_v3.ts | 2 +- .../deploy/pricing/price_adapter_algebra.ts | 42 + ...LenderCommitmentGroup_Pool_V3_Override.sol | 145 ++ .../LenderCommitmentGroup_Pool_V3_Test.sol | 1404 +++++++++++++++++ .../tests_fork/ApeChain_PoolsV3_Test.sol | 245 +++ .../tests_fork/PriceAdapterAlgebra_Test.sol | 267 ++++ 10 files changed, 2310 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/contracts/interfaces/defi/IAlgebraPool.sol create mode 100644 packages/contracts/contracts/mock/MockPriceAdapter.sol create mode 100644 packages/contracts/contracts/price_adapters/PriceAdapterAlgebra.sol create mode 100644 packages/contracts/deploy/pricing/price_adapter_algebra.ts create mode 100644 packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Override.sol create mode 100644 packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Test.sol create mode 100644 packages/contracts/tests_fork/ApeChain_PoolsV3_Test.sol create mode 100644 packages/contracts/tests_fork/PriceAdapterAlgebra_Test.sol diff --git a/packages/contracts/contracts/interfaces/defi/IAlgebraPool.sol b/packages/contracts/contracts/interfaces/defi/IAlgebraPool.sol new file mode 100644 index 000000000..93a3073e0 --- /dev/null +++ b/packages/contracts/contracts/interfaces/defi/IAlgebraPool.sol @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: AGPL-3.0 +pragma solidity ^0.8.0; + +/** + * @title IAlgebraPool + * @notice Interface for Algebra V1 pools (used by Camelot V3 on ApeChain). + * Algebra pools use globalState() and getTimepoints() instead of + * Uniswap V3's slot0() and observe(). + */ +interface IAlgebraPool { + function token0() external view returns (address); + function token1() external view returns (address); + + function globalState() external view returns ( + uint160 price, + int24 tick, + uint16 feeZto, + uint16 feeOtz, + uint16 timepointIndex, + uint8 communityFeeToken0, + uint8 communityFeeToken1, + bool unlocked + ); + + function getTimepoints(uint32[] calldata secondsAgos) external view returns ( + int56[] memory tickCumulatives, + uint160[] memory secondsPerLiquidityCumulatives + ); +} diff --git a/packages/contracts/contracts/mock/MockPriceAdapter.sol b/packages/contracts/contracts/mock/MockPriceAdapter.sol new file mode 100644 index 000000000..4dd1ef39d --- /dev/null +++ b/packages/contracts/contracts/mock/MockPriceAdapter.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "../interfaces/IPriceAdapter.sol"; + +contract MockPriceAdapter is IPriceAdapter { + uint256 public mockPriceRatioQ96; + mapping(bytes32 => bytes) public priceRoutes; + + function setMockPriceRatioQ96(uint256 _price) external { + mockPriceRatioQ96 = _price; + } + + function registerPriceRoute(bytes memory route) external returns (bytes32) { + bytes32 routeHash = keccak256(route); + priceRoutes[routeHash] = route; + return routeHash; + } + + function getPriceRatioQ96(bytes32 route) external view returns (uint256) { + require(priceRoutes[route].length > 0, "Route not found"); + return mockPriceRatioQ96; + } +} diff --git a/packages/contracts/contracts/price_adapters/PriceAdapterAlgebra.sol b/packages/contracts/contracts/price_adapters/PriceAdapterAlgebra.sol new file mode 100644 index 000000000..fb2f721aa --- /dev/null +++ b/packages/contracts/contracts/price_adapters/PriceAdapterAlgebra.sol @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// Interfaces +import "../interfaces/IPriceAdapter.sol"; +import "../interfaces/defi/IAlgebraPool.sol"; + +import {FixedPointQ96} from "../libraries/FixedPointQ96.sol"; +import {FullMath} from "../libraries/uniswap/FullMath.sol"; +import {TickMath} from "../libraries/uniswap/TickMath.sol"; + +/* + + Price adapter for Algebra V1 pools (Camelot V3 on ApeChain). + Uses globalState() instead of slot0() and getTimepoints() instead of observe(). + +*/ + +contract PriceAdapterAlgebra is IPriceAdapter { + + struct PoolRoute { + address pool; + bool zeroForOne; + uint32 twapInterval; + uint256 token0Decimals; + uint256 token1Decimals; + } + + mapping(bytes32 => bytes) public priceRoutes; + + /* Events */ + + event RouteRegistered(bytes32 hash, bytes route); + + /* External Functions */ + + function registerPriceRoute( + bytes memory route + ) external returns (bytes32 hash) { + + PoolRoute[] memory route_array = decodePoolRoutes( route ); + + require( route_array.length ==1 || route_array.length ==2, "invalid route length" ); + + // hash the route with keccak256 + bytes32 poolRouteHash = keccak256(route); + + // store the route by its hash in the priceRoutes mapping + priceRoutes[poolRouteHash] = route; + + emit RouteRegistered(poolRouteHash, route); + + return poolRouteHash; + } + + function getPriceRatioQ96( + bytes32 route + ) external view returns ( uint256 priceRatioQ96 ) { + + // lookup the route from the mapping + bytes memory routeData = priceRoutes[route]; + require(routeData.length > 0, "Route not found"); + + // decode the route + PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData); + + // start with Q96 = 1.0 in Q96 format + priceRatioQ96 = FixedPointQ96.Q96; + + // iterate through each pool and multiply prices + for (uint256 i = 0; i < poolRoutes.length; i++) { + uint256 poolPriceQ96 = getAlgebraPriceRatioForPool(poolRoutes[i]); + // multiply using Q96 arithmetic + priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96); + } + } + + // ------- + + function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) { + + encoded = abi.encode(routes); + + } + + function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) { + + route_array = abi.decode(data, (PoolRoute[])); + + require(route_array.length == 1 || route_array.length == 2, "Route must have 1 or 2 pools"); + + } + + // ------- + + function getAlgebraPriceRatioForPool( + PoolRoute memory _poolRoute + ) internal view returns (uint256 priceRatioQ96) { + + // this is expanded by 2**96 + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRoute.pool, + _poolRoute.twapInterval + ); + + // Convert sqrtPriceX96 to priceQ96 + // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format + priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96); + + // If we need the inverse (token0 in terms of token1), invert + bool invert = !_poolRoute.zeroForOne; + if (invert) { + // To invert a Q96 number: (Q96 * Q96) / value + priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96); + } + } + + function getSqrtTwapX96(address algebraPool, uint32 twapInterval) + internal + view + returns (uint160 sqrtPriceX96) + { + if (twapInterval == 0) { + // return the current price from globalState (Algebra equivalent of slot0) + (sqrtPriceX96, , , , , , , ) = IAlgebraPool(algebraPool).globalState(); + } else { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = twapInterval + 1; // from (before) + secondsAgos[1] = 1; // one block prior + + (int56[] memory tickCumulatives, ) = IAlgebraPool(algebraPool) + .getTimepoints(secondsAgos); + + // tick(imprecise as it's an integer) to price + sqrtPriceX96 = TickMath.getSqrtRatioAtTick( + int24( + (tickCumulatives[1] - tickCumulatives[0]) / + int32(twapInterval) + ) + ); + } + } + + function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceQ96) + { + // sqrtPriceX96^2 / 2^96 = priceQ96 + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96); + } +} diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts index ab8cb1687..cce31acd6 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_commitment_group_v3_beacon.ts @@ -80,6 +80,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm'].includes(hre.network.name) + return !hre.network.live || !['sepolia', 'polygon' , 'mainnet','mainnet_live_fork','arbitrum','base','optimism','katana','hyperevm','apechain'].includes(hre.network.name) } export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts index 54344279c..eb7b0d1a2 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/extensions/lender_groups_v3/lender_groups_factory_v3.ts @@ -44,6 +44,6 @@ deployFn.dependencies = [ ] deployFn.skip = async (hre) => { - return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism' ,'katana','hyperevm'].includes(hre.network.name) + return !hre.network.live || !['sepolia','polygon','mainnet','mainnet_live_fork','arbitrum','base','optimism' ,'katana','hyperevm','apechain'].includes(hre.network.name) } export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/pricing/price_adapter_algebra.ts b/packages/contracts/deploy/pricing/price_adapter_algebra.ts new file mode 100644 index 000000000..3be80c926 --- /dev/null +++ b/packages/contracts/deploy/pricing/price_adapter_algebra.ts @@ -0,0 +1,42 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + + + + const { deployer } = await hre.getNamedAccounts() + + // Deploy FixedPointQ96 library first + const FixedPointQ96 = await hre.deployments.deploy('FixedPointQ96', { + from: deployer, + }) + + hre.log('FixedPointQ96 library deployed at:' ) + hre.log( FixedPointQ96.address) + + + + // Deploy PriceAdapterAlgebra with linked library + const PriceAdapterAlgebra = await hre.deployments.deploy('PriceAdapterAlgebra', { + from: deployer, + libraries: { + FixedPointQ96: FixedPointQ96.address, + }, + }) + + hre.log('PriceAdapterAlgebra deployed at:' ) + hre.log( PriceAdapterAlgebra.address) + + +} + +// tags and deployment +deployFn.id = 'price-adapter-algebra:deploy' +deployFn.tags = ['teller-v2', 'price-adapter-algebra:deploy'] +deployFn.dependencies = [] + +deployFn.skip = async (hre) => { + return !hre.network.live || ![ 'apechain' ].includes(hre.network.name) + } + +export default deployFn diff --git a/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Override.sol b/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Override.sol new file mode 100644 index 000000000..2457ae484 --- /dev/null +++ b/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Override.sol @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/Address.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +import { LenderCommitmentGroup_Pool_V3 } from "../../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol"; + +contract LenderCommitmentGroup_Pool_V3_Override is LenderCommitmentGroup_Pool_V3 { + uint256 mockRequiredCollateralAmount; + uint256 mockSharesExchangeRate; + int256 mockMinimumAmountDifferenceToCloseDefaultedLoan; + + uint256 mockLoanTotalPrincipalAmount; + + uint256 mockAmountOwedPrincipal; + uint256 mockAmountOwedInterest; + + bool mockFirstDepositMade; + + constructor(address _tellerV2, address _smartCommitmentForwarder) + LenderCommitmentGroup_Pool_V3(_tellerV2, _smartCommitmentForwarder) + {} + + function set_mockSharesExchangeRate(uint256 _mockRate) public { + mockSharesExchangeRate = _mockRate; + } + + function set_mockBidAsActiveForGroup(uint256 _bidId, bool _active) public { + activeBids[_bidId] = _active; + } + + function mock_setMinimumAmountDifferenceToCloseDefaultedLoan( + int256 _amt + ) external { + mockMinimumAmountDifferenceToCloseDefaultedLoan = _amt; + } + + function getMinimumAmountDifferenceToCloseDefaultedLoan( + uint256 _amountOwed, + uint256 _loanDefaultedTimestamp + ) public view override returns (int256 amountDifference_) { + return mockMinimumAmountDifferenceToCloseDefaultedLoan; + } + + function super_getMinimumAmountDifferenceToCloseDefaultedLoan( + uint256 _amountOwed, + uint256 _loanDefaultedTimestamp + ) public view returns (int256) { + return super.getMinimumAmountDifferenceToCloseDefaultedLoan(_amountOwed, _loanDefaultedTimestamp); + } + + function _getAmountOwedForBid(uint256 _bidId) + internal view override returns (uint256, uint256) { + return (mockAmountOwedPrincipal, mockAmountOwedInterest); + } + + function set_mockAmountOwedForBid(uint256 _principal, uint256 _interest) public { + mockAmountOwedPrincipal = _principal; + mockAmountOwedInterest = _interest; + } + + function _getLoanTotalPrincipalAmount(uint256 _bidId) + internal view override returns (uint256) { + return mockLoanTotalPrincipalAmount; + } + + function set_mockLoanTotalPrincipalAmount(uint256 _principal) public { + mockLoanTotalPrincipalAmount = _principal; + } + + function set_mockActiveBidsAmountDueRemaining(uint256 _bidId, uint256 _amount) public { + activeBidsAmountDueRemaining[_bidId] = _amount; + } + + function set_totalPrincipalTokensLended(uint256 _mockAmt) public { + totalPrincipalTokensLended = _mockAmt; + } + + function set_totalPrincipalTokensRepaid(uint256 _mockAmt) public { + totalPrincipalTokensRepaid = _mockAmt; + } + + function set_totalPrincipalTokensCommitted(uint256 _mockAmt) public { + totalPrincipalTokensCommitted = _mockAmt; + } + + function set_totalPrincipalTokensWithdrawn(uint256 _mockAmt) public { + totalPrincipalTokensWithdrawn = _mockAmt; + } + + function set_totalInterestCollected(uint256 _mockAmt) public { + totalInterestCollected = _mockAmt; + } + + function set_tokenDifferenceFromLiquidations(int256 _mockAmt) public { + tokenDifferenceFromLiquidations = _mockAmt; + } + + function set_mock_requiredCollateralAmount(uint256 amt) public { + mockRequiredCollateralAmount = amt; + } + + function force_mint_shares(address guy, uint256 wad) public { + return super.mintShares(guy, wad); + } + + function force_set_withdraw_delay(uint256 _delay) public { + withdrawDelayTimeSeconds = _delay; + } + + function force_set_firstDepositMade(bool _made) public { + firstDepositMade = _made; + } + + function sharesExchangeRate() public view override returns (uint256 rate_) { + if (mockSharesExchangeRate > 0) { + return mockSharesExchangeRate; + } + return super.sharesExchangeRate(); + } + + function super_sharesExchangeRate() public view returns (uint256) { + return super.sharesExchangeRate(); + } + + function super_sharesExchangeRateInverse() public view returns (uint256) { + return super.sharesExchangeRateInverse(); + } + + function mock_setBidActive(uint256 _bidId) public { + activeBids[_bidId] = true; + } + + function getRequiredCollateral( + uint256 _principalAmount, + uint256 maxPrincipalPerCollateralAmount + ) internal view override returns (uint256) { + return mockRequiredCollateralAmount; + } + + function public_getPoolTotalEstimatedValue() public view returns (uint256) { + return getPoolTotalEstimatedValue(); + } +} diff --git a/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Test.sol b/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Test.sol new file mode 100644 index 000000000..960daa8a4 --- /dev/null +++ b/packages/contracts/tests/SmartCommitmentForwarder/LenderCommitmentGroup_Pool_V3_Test.sol @@ -0,0 +1,1404 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Testable } from "../Testable.sol"; + +import { LenderCommitmentGroup_Pool_V3_Override } from "./LenderCommitmentGroup_Pool_V3_Override.sol"; + +import {TestERC20Token} from "../tokens/TestERC20Token.sol"; + +import {MarketRegistry} from "../../contracts/MarketRegistry.sol"; +import {SmartCommitmentForwarder} from "../../contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol"; +import {TellerV2SolMock} from "../../contracts/mock/TellerV2SolMock.sol"; +import {MockPriceAdapter} from "../../contracts/mock/MockPriceAdapter.sol"; +import { PaymentType, PaymentCycleType } from "../../contracts/libraries/V2Calculations.sol"; +import { LoanDetails, Payment, BidState , Bid, Terms } from "../../contracts/TellerV2Storage.sol"; + +import { ILenderCommitmentGroup_V3 } from "../../contracts/interfaces/ILenderCommitmentGroup_V3.sol"; +import { IPriceAdapter } from "../../contracts/interfaces/IPriceAdapter.sol"; + +import {ILenderCommitmentGroupSharesIntegrated} from "../../contracts/interfaces/ILenderCommitmentGroupSharesIntegrated.sol"; + +import {ProtocolPausingManager} from "../../contracts/pausing/ProtocolPausingManager.sol"; + +import "lib/forge-std/src/console.sol"; +import "lib/forge-std/src/Vm.sol"; + +// Helper contract to simulate a user +contract User {} + +contract LenderCommitmentGroup_Pool_V3_Test is Testable { + constructor() {} + + User private borrower; + User private lender; + User private liquidator; + + TestERC20Token principalToken; + TestERC20Token collateralToken; + + LenderCommitmentGroup_Pool_V3_Override lenderCommitmentGroupV3; + + MarketRegistry _marketRegistry; + TellerV2SolMock _tellerV2; + SmartCommitmentForwarder _smartCommitmentForwarder; + MockPriceAdapter _mockPriceAdapter; + + ProtocolPausingManager _protocolPausingManager; + + // Q96 = 2^96, used for price ratio + uint256 constant Q96 = 0x1000000000000000000000000; + + function setUp() public { + borrower = new User(); + lender = new User(); + liquidator = new User(); + + _tellerV2 = new TellerV2SolMock(); + _marketRegistry = new MarketRegistry(); + _smartCommitmentForwarder = new SmartCommitmentForwarder( + address(_tellerV2), address(_marketRegistry)); + + _mockPriceAdapter = new MockPriceAdapter(); + // Set a reasonable default price: 1:1 in Q96 format + _mockPriceAdapter.setMockPriceRatioQ96(Q96); + + _protocolPausingManager = new ProtocolPausingManager(); + _protocolPausingManager.initialize(); + + _tellerV2.setProtocolPausingManager(address(_protocolPausingManager)); + + principalToken = new TestERC20Token("wrappedETH", "WETH", 1e24, 18); + collateralToken = new TestERC20Token("PEPE", "pepe", 1e24, 18); + + principalToken.transfer(address(lender), 1e18); + collateralToken.transfer(address(borrower), 1e18); + principalToken.transfer(address(liquidator), 1e18); + + lenderCommitmentGroupV3 = new LenderCommitmentGroup_Pool_V3_Override( + address(_tellerV2), + address(_smartCommitmentForwarder) + ); + } + + function _buildPriceAdapterRoute() internal view returns (bytes memory) { + // Encode a dummy route - the mock adapter doesn't care about content + // but registerPriceRoute needs non-empty bytes + bytes memory route = abi.encode( + address(principalToken), + address(collateralToken), + uint32(5) + ); + return route; + } + + function initialize_group_contract() public { + address _principalTokenAddress = address(principalToken); + address _collateralTokenAddress = address(collateralToken); + uint256 _marketId = 1; + uint32 _maxLoanDuration = 5000000; + uint16 _interestRateLowerBound = 0; + uint16 _interestRateUpperBound = 800; + uint16 _liquidityThresholdPercent = 10000; + uint16 _collateralRatio = 10000; + + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory groupConfig = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: _principalTokenAddress, + collateralTokenAddress: _collateralTokenAddress, + marketId: _marketId, + maxLoanDuration: _maxLoanDuration, + interestRateLowerBound: _interestRateLowerBound, + interestRateUpperBound: _interestRateUpperBound, + liquidityThresholdPercent: _liquidityThresholdPercent, + collateralRatio: _collateralRatio + }); + + bytes memory route = _buildPriceAdapterRoute(); + + lenderCommitmentGroupV3.initialize( + groupConfig, + address(_mockPriceAdapter), + route + ); + } + + // ============ Initialization Tests ============ + + function test_initialize() public { + address _principalTokenAddress = address(principalToken); + address _collateralTokenAddress = address(collateralToken); + uint256 _marketId = 1; + uint32 _maxLoanDuration = 5000000; + uint16 _interestRateLowerBound = 100; + uint16 _interestRateUpperBound = 800; + uint16 _liquidityThresholdPercent = 10000; + uint16 _collateralRatio = 10000; + + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory groupConfig = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: _principalTokenAddress, + collateralTokenAddress: _collateralTokenAddress, + marketId: _marketId, + maxLoanDuration: _maxLoanDuration, + interestRateLowerBound: _interestRateLowerBound, + interestRateUpperBound: _interestRateUpperBound, + liquidityThresholdPercent: _liquidityThresholdPercent, + collateralRatio: _collateralRatio + }); + + bytes memory route = _buildPriceAdapterRoute(); + + lenderCommitmentGroupV3.initialize( + groupConfig, + address(_mockPriceAdapter), + route + ); + + // Verify state was set + assertEq(address(lenderCommitmentGroupV3.principalToken()), _principalTokenAddress); + assertEq(address(lenderCommitmentGroupV3.collateralToken()), _collateralTokenAddress); + assertEq(lenderCommitmentGroupV3.priceAdapter(), address(_mockPriceAdapter)); + assertTrue(lenderCommitmentGroupV3.priceRouteHash() != bytes32(0), "Price route hash should be set"); + } + + function test_initialize_reverts_invalid_interest_rates() public { + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory groupConfig = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: address(principalToken), + collateralTokenAddress: address(collateralToken), + marketId: 1, + maxLoanDuration: 5000000, + interestRateLowerBound: 900, + interestRateUpperBound: 800, // lower > upper + liquidityThresholdPercent: 10000, + collateralRatio: 10000 + }); + + bytes memory route = _buildPriceAdapterRoute(); + + vm.expectRevert(bytes("IRLB")); + lenderCommitmentGroupV3.initialize( + groupConfig, + address(_mockPriceAdapter), + route + ); + } + + function test_initialize_reverts_invalid_liquidity_threshold() public { + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory groupConfig = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: address(principalToken), + collateralTokenAddress: address(collateralToken), + marketId: 1, + maxLoanDuration: 5000000, + interestRateLowerBound: 100, + interestRateUpperBound: 800, + liquidityThresholdPercent: 10001, // > 10000 + collateralRatio: 10000 + }); + + bytes memory route = _buildPriceAdapterRoute(); + + vm.expectRevert(bytes("ILTP")); + lenderCommitmentGroupV3.initialize( + groupConfig, + address(_mockPriceAdapter), + route + ); + } + + function test_initialize_cannot_reinitialize() public { + initialize_group_contract(); + + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory groupConfig = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: address(principalToken), + collateralTokenAddress: address(collateralToken), + marketId: 1, + maxLoanDuration: 5000000, + interestRateLowerBound: 100, + interestRateUpperBound: 800, + liquidityThresholdPercent: 10000, + collateralRatio: 10000 + }); + + bytes memory route = _buildPriceAdapterRoute(); + + vm.expectRevert(); + lenderCommitmentGroupV3.initialize( + groupConfig, + address(_mockPriceAdapter), + route + ); + } + + // ============ ERC4626 Deposit Tests ============ + + function test_erc4626_deposit_first_deposit_only_owner() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), 1000000); + + // Non-owner should fail with "FDM" (First Deposit Made check) + vm.prank(address(lender)); + vm.expectRevert(); + lenderCommitmentGroupV3.deposit(1000000, address(lender)); + } + + function test_erc4626_deposit() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.force_set_firstDepositMade(true); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), 1000000); + + vm.prank(address(lender)); + uint256 sharesAmount = lenderCommitmentGroupV3.deposit(1000000, address(lender)); + + uint256 expectedSharesAmount = 1000000; + assertEq( + sharesAmount, + expectedSharesAmount, + "Received an unexpected amount of shares" + ); + } + + function test_erc4626_deposit_first_deposit_by_owner() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + // The test contract is the owner after initialize + principalToken.approve(address(lenderCommitmentGroupV3), 2e6); + + // Owner can make the first deposit, must be >= 1e6 shares + uint256 sharesAmount = lenderCommitmentGroupV3.deposit(2e6, address(this)); + assertGe(sharesAmount, 1e6, "First deposit shares should be >= 1e6"); + assertTrue(lenderCommitmentGroupV3.firstDepositMade(), "firstDepositMade should be true"); + } + + function test_erc4626_deposit_first_deposit_too_small() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + // Owner tries first deposit but too small (< 1e6 shares) + principalToken.approve(address(lenderCommitmentGroupV3), 100); + + vm.expectRevert(bytes("IS")); + lenderCommitmentGroupV3.deposit(100, address(this)); + } + + // ============ ERC4626 Mint Tests ============ + + function test_erc4626_mint() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.force_set_firstDepositMade(true); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), 1000000); + + vm.prank(address(lender)); + uint256 assetsAmount = lenderCommitmentGroupV3.mint(1000000, address(lender)); + + uint256 expectedAssetsAmount = 1000000; + assertEq( + assetsAmount, + expectedAssetsAmount, + "Used an unexpected amount of assets" + ); + } + + // ============ ERC4626 Redeem Tests ============ + + function test_erc4626_redeem() public { + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.warp(1e6); + + // Mint shares to lender + uint256 sharesAmount = 1000000; + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + vm.warp(1e7); + + vm.prank(address(lender)); + uint256 assetsReceived = lenderCommitmentGroupV3.redeem( + sharesAmount, + address(lender), + address(lender) + ); + + uint256 expectedAssetsReceived = 1000000; + assertEq( + assetsReceived, + expectedAssetsReceived, + "Received an unexpected amount of assets" + ); + } + + // ============ ERC4626 Withdraw Tests ============ + + function test_erc4626_withdraw() public { + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.warp(1e6); + + // Mint shares to lender + uint256 sharesAmount = 1000000; + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + vm.warp(1e7); + + vm.prank(address(lender)); + uint256 sharesRedeemedAmount = lenderCommitmentGroupV3.withdraw( + 1000000, + address(lender), + address(lender) + ); + + uint256 expectedSharesRedeemed = 1000000; + assertEq( + sharesRedeemedAmount, + expectedSharesRedeemed, + "Burned an unexpected amount of shares" + ); + } + + function test_erc4626_withdraw_fails_without_warp() public { + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.warp(1e6); + + // Mint shares to lender + uint256 sharesAmount = 1000000; + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + // Don't warp — shares were just transferred + + uint256 sharesLastTransferredAt = ILenderCommitmentGroupSharesIntegrated(address(lenderCommitmentGroupV3)).getSharesLastTransferredAt(address(lender)); + assertEq(sharesLastTransferredAt, 1e6, "unexpected sharesLastTransferredAt"); + + lenderCommitmentGroupV3.force_set_withdraw_delay(9000); + + vm.expectRevert(); + vm.prank(address(lender)); + lenderCommitmentGroupV3.withdraw( + 1000000, + address(lender), + address(lender) + ); + } + + function test_erc4626_withdraw_unauthorized() public { + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.warp(1e6); + + uint256 sharesAmount = 1000000; + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + vm.warp(1e7); + + // Borrower tries to withdraw lender's shares + vm.expectRevert(bytes("UA")); + vm.prank(address(borrower)); + lenderCommitmentGroupV3.withdraw( + 1000000, + address(borrower), + address(lender) + ); + } + + function test_erc4626_redeem_unauthorized() public { + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.warp(1e6); + + uint256 sharesAmount = 1000000; + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + vm.warp(1e7); + + // Borrower tries to redeem lender's shares + vm.expectRevert(bytes("UA")); + vm.prank(address(borrower)); + lenderCommitmentGroupV3.redeem( + sharesAmount, + address(borrower), + address(lender) + ); + } + + // ============ ERC4626 Accounting Tests ============ + + function test_erc4626_accounting() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalInterestCollected(500000); + + // Test totalAssets() + uint256 totalAssets = lenderCommitmentGroupV3.totalAssets(); + assertEq(totalAssets, 1500000, "Incorrect total assets calculation"); + + // Test convertToShares/convertToAssets with 1:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + uint256 shares = lenderCommitmentGroupV3.convertToShares(1000); + assertEq(shares, 1000, "Incorrect shares conversion"); + + uint256 assets = lenderCommitmentGroupV3.convertToAssets(1000); + assertEq(assets, 1000, "Incorrect assets conversion"); + + // Test with 2:1 exchange rate (1 share = 2 assets) + lenderCommitmentGroupV3.set_mockSharesExchangeRate(2 * 1e36); + + shares = lenderCommitmentGroupV3.convertToShares(1000); + assertEq(shares, 500, "Incorrect shares conversion with 2:1 rate"); + + assets = lenderCommitmentGroupV3.convertToAssets(500); + assertEq(assets, 1000, "Incorrect assets conversion with 2:1 rate"); + } + + function test_totalAssets_with_withdrawals() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalInterestCollected(200000); + lenderCommitmentGroupV3.set_totalPrincipalTokensWithdrawn(300000); + + uint256 totalAssets = lenderCommitmentGroupV3.totalAssets(); + // 1000000 + 200000 - 300000 = 900000 + assertEq(totalAssets, 900000, "totalAssets should account for withdrawals"); + } + + function test_totalAssets_with_liquidation_losses() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_tokenDifferenceFromLiquidations(-500000); + + uint256 totalAssets = lenderCommitmentGroupV3.totalAssets(); + // 1000000 - 500000 = 500000 + assertEq(totalAssets, 500000, "totalAssets should account for liquidation losses"); + } + + function test_totalAssets_floors_at_zero() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(100000); + lenderCommitmentGroupV3.set_tokenDifferenceFromLiquidations(-500000); + + uint256 totalAssets = lenderCommitmentGroupV3.totalAssets(); + // Would be negative, floored to 0 + assertEq(totalAssets, 0, "totalAssets should floor at zero"); + } + + // ============ Lending (acceptFundsForAcceptBid) Tests ============ + + function test_acceptFundsForAcceptBid() public { + lenderCommitmentGroupV3.set_mock_requiredCollateralAmount(100); + + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + collateralToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + uint256 principalAmount = 50; + uint256 collateralAmount = 100; + + address collateralTokenAddress = address(lenderCommitmentGroupV3.collateralToken()); + uint256 collateralTokenId = 0; + + uint32 loanDuration = 5000000; + uint16 interestRate = 100; + + uint256 bidId = 0; + + // submit bid + TellerV2SolMock(_tellerV2).submitBid( + address(principalToken), + 0, + principalAmount, + loanDuration, + interestRate, + "", + address(this) + ); + + vm.prank(address(_smartCommitmentForwarder)); + lenderCommitmentGroupV3.acceptFundsForAcceptBid( + address(borrower), + bidId, + principalAmount, + collateralAmount, + collateralTokenAddress, + collateralTokenId, + loanDuration, + interestRate + ); + } + + function test_acceptFundsForAcceptBid_insufficientCollateral() public { + lenderCommitmentGroupV3.set_mock_requiredCollateralAmount(100); + + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + collateralToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + uint256 principalAmount = 100; + uint256 collateralAmount = 0; // insufficient + + address collateralTokenAddress = address(lenderCommitmentGroupV3.collateralToken()); + uint256 collateralTokenId = 0; + + uint32 loanDuration = 5000000; + uint16 interestRate = 100; + + uint256 bidId = 0; + + vm.expectRevert(bytes("C")); + vm.prank(address(_smartCommitmentForwarder)); + lenderCommitmentGroupV3.acceptFundsForAcceptBid( + address(borrower), + bidId, + principalAmount, + collateralAmount, + collateralTokenAddress, + collateralTokenId, + loanDuration, + interestRate + ); + } + + function test_acceptFundsForAcceptBid_wrongCollateralToken() public { + lenderCommitmentGroupV3.set_mock_requiredCollateralAmount(100); + + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + vm.expectRevert(bytes("MMCT")); + vm.prank(address(_smartCommitmentForwarder)); + lenderCommitmentGroupV3.acceptFundsForAcceptBid( + address(borrower), + 0, + 100, + 100, + address(principalToken), // wrong token + 0, + 5000000, + 100 + ); + } + + function test_acceptFundsForAcceptBid_loanDurationTooLong() public { + lenderCommitmentGroupV3.set_mock_requiredCollateralAmount(100); + + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + address collateralTokenAddress = address(lenderCommitmentGroupV3.collateralToken()); + + vm.expectRevert(bytes("LMD")); + vm.prank(address(_smartCommitmentForwarder)); + lenderCommitmentGroupV3.acceptFundsForAcceptBid( + address(borrower), + 0, + 100, + 200, + collateralTokenAddress, + 0, + 5000001, // exceeds maxLoanDuration + 100 + ); + } + + function test_acceptFundsForAcceptBid_onlySmartCommitmentForwarder() public { + lenderCommitmentGroupV3.set_mock_requiredCollateralAmount(100); + + principalToken.transfer(address(lenderCommitmentGroupV3), 1e18); + + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + address collateralTokenAddress = address(lenderCommitmentGroupV3.collateralToken()); + + vm.expectRevert(bytes("OSCF")); + // Not called from SCF + lenderCommitmentGroupV3.acceptFundsForAcceptBid( + address(borrower), + 0, + 100, + 200, + collateralTokenAddress, + 0, + 5000000, + 100 + ); + } + + // ============ Repayment Callback Tests ============ + + function test_repayLoanCallback() public { + uint256 principalAmount = 100; + uint256 interestAmount = 50; + address repayer = address(borrower); + + uint256 bidId = 0; + + lenderCommitmentGroupV3.mock_setBidActive(bidId); + lenderCommitmentGroupV3.set_mockActiveBidsAmountDueRemaining(bidId, principalAmount); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.repayLoanCallback( + bidId, + address(repayer), + principalAmount, + interestAmount + ); + } + + function test_repayLoanCallback_bid_not_active() public { + uint256 principalAmount = 100; + uint256 interestAmount = 50; + address repayer = address(borrower); + + uint256 bidId = 0; + + vm.expectRevert(bytes("BNA")); + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.repayLoanCallback( + bidId, + address(repayer), + principalAmount, + interestAmount + ); + } + + function test_repayLoanCallback_onlyTellerV2() public { + uint256 bidId = 0; + lenderCommitmentGroupV3.mock_setBidActive(bidId); + lenderCommitmentGroupV3.set_mockActiveBidsAmountDueRemaining(bidId, 100); + + vm.expectRevert(bytes("OTV2")); + lenderCommitmentGroupV3.repayLoanCallback( + bidId, + address(borrower), + 100, + 50 + ); + } + + // ============ Liquidation Tests ============ + + function test_liquidation_bid_not_active() public { + initialize_group_contract(); + + vm.warp(1e10); + + uint256 marketId = 0; + uint256 principalAmount = 100; + uint32 loanDuration = 500000; + uint16 interestRate = 50; + + uint256 bidId = TellerV2SolMock(_tellerV2).submitBid( + address(principalToken), + marketId, + principalAmount, + loanDuration, + interestRate, + "", + address(borrower) + ); + + vm.prank(address(lender)); + principalToken.approve(address(_tellerV2), 1000000); + + vm.prank(address(lender)); + TellerV2SolMock(_tellerV2).lenderAcceptBid(bidId); + + vm.warp(1e20); + + int256 tokenAmountDifference = 10000; + + vm.expectRevert(bytes("BNA")); + lenderCommitmentGroupV3.liquidateDefaultedLoanWithIncentive( + bidId, + tokenAmountDifference + ); + } + + function test_liquidation_handles_partially_repaid_loan() public { + initialize_group_contract(); + + vm.warp(10000000000); + + uint256 marketId = 0; + uint256 principalAmount = 900; + uint32 loanDuration = 500000; + uint16 interestRate = 50; + + uint256 bidId = TellerV2SolMock(_tellerV2).submitBid( + address(principalToken), + marketId, + principalAmount, + loanDuration, + interestRate, + "", + address(borrower) + ); + + vm.prank(address(lender)); + principalToken.approve(address(_tellerV2), 1000000); + + vm.prank(address(lender)); + TellerV2SolMock(_tellerV2).lenderAcceptBid(bidId); + + lenderCommitmentGroupV3.set_mockBidAsActiveForGroup(bidId, true); + lenderCommitmentGroupV3.set_mockActiveBidsAmountDueRemaining(bidId, principalAmount); + + uint256 principalTokensCommitted = 4000; + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(principalTokensCommitted); + + _tellerV2.mock_setLoanDefaultTimestamp(block.timestamp - 1000); + + lenderCommitmentGroupV3.mock_setMinimumAmountDifferenceToCloseDefaultedLoan(500); + + vm.prank(address(liquidator)); + principalToken.approve(address(lenderCommitmentGroupV3), principalAmount + 500); + + vm.prank(address(liquidator)); + lenderCommitmentGroupV3.liquidateDefaultedLoanWithIncentive( + bidId, + 500 + ); + } + + // ============ Liquidation Auction Math Tests ============ + + function test_getMinimumAmountDifferenceToCloseDefaultedLoan() public { + initialize_group_contract(); + + uint256 amountDue = 500; + + vm.warp(10000); + uint256 loanDefaultTimestamp = block.timestamp - 2000; + + int256 min_amount = lenderCommitmentGroupV3.super_getMinimumAmountDifferenceToCloseDefaultedLoan( + amountDue, + loanDefaultTimestamp + ); + + int256 expectedMinAmount = 3720; // (86400 - 10000 - 2000) / 10000 * 500 + assertEq(min_amount, expectedMinAmount, "min_amount unexpected"); + } + + function test_getMinimumAmountDifferenceToCloseDefaultedLoan_zero_time() public { + initialize_group_contract(); + + uint256 amountDue = 500; + + vm.warp(10000); + uint256 loanDefaultTimestamp = block.timestamp; + + vm.expectRevert(bytes("LDT")); + lenderCommitmentGroupV3.super_getMinimumAmountDifferenceToCloseDefaultedLoan( + amountDue, + loanDefaultTimestamp + ); + } + + function test_getMinimumAmountDifferenceToCloseDefaultedLoan_full_time() public { + initialize_group_contract(); + + uint256 amountDue = 500; + + vm.warp(100000); + uint256 loanDefaultTimestamp = block.timestamp - 22000; + + int256 min_amount = lenderCommitmentGroupV3.super_getMinimumAmountDifferenceToCloseDefaultedLoan( + amountDue, + loanDefaultTimestamp + ); + + int256 expectedMinAmount = 2720; + assertEq(min_amount, expectedMinAmount, "min_amount unexpected"); + } + + function test_getMinimumAmountDifferenceToCloseDefaultedLoan_fully_expired() public { + initialize_group_contract(); + + uint256 amountDue = 500; + + vm.warp(200000); + // Over 96400 seconds since default => capped at -10000 + uint256 loanDefaultTimestamp = block.timestamp - 100000; + + int256 min_amount = lenderCommitmentGroupV3.super_getMinimumAmountDifferenceToCloseDefaultedLoan( + amountDue, + loanDefaultTimestamp + ); + + // incentiveMultiplier capped at -10000, so: 500 * -10000 / 10000 = -500 + int256 expectedMinAmount = -500; + assertEq(min_amount, expectedMinAmount, "min_amount should be capped at -amountDue"); + } + + // ============ Exchange Rate Tests ============ + + function test_get_shares_exchange_rate_scenario_A() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalInterestCollected(0); + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(5000000); + + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 1e36, "unexpected sharesExchangeRate"); + } + + function test_get_shares_exchange_rate_scenario_B() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalInterestCollected(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensWithdrawn(1000000); + + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 1e36, "unexpected sharesExchangeRate"); + } + + function test_get_shares_exchange_rate_scenario_C() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalInterestCollected(1000000); + + uint256 sharesAmount = 500000; + + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + uint256 poolTotalEstimatedValue = lenderCommitmentGroupV3.public_getPoolTotalEstimatedValue(); + assertEq(poolTotalEstimatedValue, 2 * 1000000, "unexpected poolTotalEstimatedValue"); + + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 4 * 1e36, "unexpected sharesExchangeRate"); + } + + function test_get_shares_exchange_rate_after_default_liquidation_A() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalInterestCollected(1000000); + lenderCommitmentGroupV3.set_tokenDifferenceFromLiquidations(-1000000); + + uint256 sharesAmount = 1000000; + + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + uint256 poolTotalEstimatedValue = lenderCommitmentGroupV3.public_getPoolTotalEstimatedValue(); + assertEq(poolTotalEstimatedValue, 1 * 1000000, "unexpected poolTotalEstimatedValue"); + + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 1 * 1e36, "unexpected sharesExchangeRate"); + } + + function test_get_shares_exchange_rate_after_default_liquidation_B() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_tokenDifferenceFromLiquidations(-500000); + + uint256 sharesAmount = 1000000; + + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), sharesAmount); + + uint256 poolTotalEstimatedValue = lenderCommitmentGroupV3.public_getPoolTotalEstimatedValue(); + assertEq(poolTotalEstimatedValue, 1 * 500000, "unexpected poolTotalEstimatedValue"); + + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 1e36 / 2, "unexpected sharesExchangeRate"); + } + + function test_sharesExchangeRate_initial_is_1to1() public { + initialize_group_contract(); + + // No shares minted, no deposits — should return EXCHANGE_RATE_EXPANSION_FACTOR (1e36) + uint256 rate = lenderCommitmentGroupV3.super_sharesExchangeRate(); + assertEq(rate, 1e36, "Initial exchange rate should be 1:1"); + } + + // ============ Pausing Tests ============ + + function test_pause_unpause() public { + initialize_group_contract(); + + address pausingManager = _tellerV2.getProtocolPausingManager(); + + vm.prank(address(this)); + _protocolPausingManager.addPauser(address(_tellerV2)); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pausePool(); + assertTrue(lenderCommitmentGroupV3.paused(), "Contract should be paused"); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.unpausePool(); + assertFalse(lenderCommitmentGroupV3.paused(), "Contract should be unpaused"); + + uint256 lastUnpausedAt = lenderCommitmentGroupV3.getLastUnpausedAt(); + assertEq(lastUnpausedAt, block.timestamp, "lastUnpausedAt not set correctly"); + } + + function test_pause_borrowing() public { + initialize_group_contract(); + + _protocolPausingManager.addPauser(address(_tellerV2)); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pauseBorrowing(); + assertTrue(lenderCommitmentGroupV3.borrowingPaused(), "Borrowing should be paused"); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.unpauseBorrowing(); + assertFalse(lenderCommitmentGroupV3.borrowingPaused(), "Borrowing should be unpaused"); + } + + function test_pause_liquidation_auction() public { + initialize_group_contract(); + + _protocolPausingManager.addPauser(address(_tellerV2)); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pauseLiquidationAuction(); + assertTrue(lenderCommitmentGroupV3.liquidationAuctionPaused(), "Liquidation auction should be paused"); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.unpauseLiquidationAuction(); + assertFalse(lenderCommitmentGroupV3.liquidationAuctionPaused(), "Liquidation auction should be unpaused"); + } + + function test_deposit_blocked_when_paused() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.force_set_firstDepositMade(true); + + _protocolPausingManager.addPauser(address(_tellerV2)); + + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pausePool(); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), 1000000); + + vm.expectRevert(bytes("P")); + vm.prank(address(lender)); + lenderCommitmentGroupV3.deposit(1000000, address(lender)); + } + + // ============ Preview Functions Tests ============ + + function test_previewDeposit() public { + initialize_group_contract(); + + // Test with 1:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + uint256 assets = 1000000; + uint256 expectedShares = 1000000; + + uint256 shares = lenderCommitmentGroupV3.previewDeposit(assets); + assertEq(shares, expectedShares, "previewDeposit should return correct shares at 1:1 rate"); + + // Test with 2:1 exchange rate (1 share = 2 assets) + lenderCommitmentGroupV3.set_mockSharesExchangeRate(2 * 1e36); + + expectedShares = 500000; + shares = lenderCommitmentGroupV3.previewDeposit(assets); + assertEq(shares, expectedShares, "previewDeposit should return correct shares at 2:1 rate"); + + // Test with 1:2 exchange rate (2 shares = 1 asset) + lenderCommitmentGroupV3.set_mockSharesExchangeRate(5e35); // 0.5 * 1e36 + + expectedShares = 2000000; + shares = lenderCommitmentGroupV3.previewDeposit(assets); + assertEq(shares, expectedShares, "previewDeposit should return correct shares at 1:2 rate"); + } + + function test_previewMint() public { + initialize_group_contract(); + + // Test with 1:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + uint256 shares = 1000000; + uint256 expectedAssets = 1000000; + + uint256 assets = lenderCommitmentGroupV3.previewMint(shares); + assertEq(assets, expectedAssets, "previewMint should return correct assets at 1:1 rate"); + + // Test with 2:1 exchange rate (1 share = 2 assets) + lenderCommitmentGroupV3.set_mockSharesExchangeRate(2 * 1e36); + + expectedAssets = 2000000; + assets = lenderCommitmentGroupV3.previewMint(shares); + assertEq(assets, expectedAssets, "previewMint should return correct assets at 2:1 rate"); + + // Test with 1:2 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(5e35); + + expectedAssets = 500000; + assets = lenderCommitmentGroupV3.previewMint(shares); + assertEq(assets, expectedAssets, "previewMint should return correct assets at 1:2 rate"); + } + + function test_previewWithdraw() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalInterestCollected(200000); + + // Test with 1:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + uint256 assets = 1000000; + uint256 expectedShares = 1000000; + + uint256 shares = lenderCommitmentGroupV3.previewWithdraw(assets); + assertEq(shares, expectedShares, "previewWithdraw should return correct shares at 1:1 rate"); + + // Test with 2:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(2 * 1e36); + + expectedShares = 500000; + shares = lenderCommitmentGroupV3.previewWithdraw(assets); + assertEq(shares, expectedShares, "previewWithdraw should return correct shares at 2:1 rate"); + + // Test with 1:2 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(5e35); + + expectedShares = 2000000; + shares = lenderCommitmentGroupV3.previewWithdraw(assets); + assertEq(shares, expectedShares, "previewWithdraw should return correct shares at 1:2 rate"); + } + + function test_previewRedeem() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + // Test with 1:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + + uint256 shares = 1000000; + uint256 expectedAssets = 1000000; + + uint256 assets = lenderCommitmentGroupV3.previewRedeem(shares); + assertEq(assets, expectedAssets, "previewRedeem should return correct assets at 1:1 rate"); + + // Test with 2:1 exchange rate + lenderCommitmentGroupV3.set_mockSharesExchangeRate(2 * 1e36); + + // 1 share = 2 assets, so 1000000 shares = 2000000 assets + expectedAssets = 2000000; + assets = lenderCommitmentGroupV3.previewRedeem(shares); + assertEq(assets, expectedAssets, "previewRedeem should return correct assets at 2:1 rate"); + } + + // ============ Preview Functions Match Actual Operations ============ + + function test_preview_functions_match_actual_operations() public { + initialize_group_contract(); + lenderCommitmentGroupV3.set_mockSharesExchangeRate(1e36); + lenderCommitmentGroupV3.force_set_firstDepositMade(true); + + // Test deposit preview matches actual deposit + uint256 depositAmount = 1000000; + uint256 expectedShares = lenderCommitmentGroupV3.previewDeposit(depositAmount); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), depositAmount); + + vm.prank(address(lender)); + uint256 actualShares = lenderCommitmentGroupV3.deposit(depositAmount, address(lender)); + + assertEq(actualShares, expectedShares, "Actual deposit shares should match preview"); + + // Test mint preview matches actual mint + uint256 mintShares = 500000; + uint256 expectedAssets = lenderCommitmentGroupV3.previewMint(mintShares); + + vm.prank(address(lender)); + principalToken.approve(address(lenderCommitmentGroupV3), expectedAssets); + + vm.prank(address(lender)); + uint256 actualAssets = lenderCommitmentGroupV3.mint(mintShares, address(lender)); + + assertEq(actualAssets, expectedAssets, "Actual mint assets should match preview"); + + // Fund the contract for withdrawal tests + principalToken.transfer(address(lenderCommitmentGroupV3), 5e18); + + // Test withdraw preview matches actual withdraw + uint256 withdrawAmount = 200000; + uint256 expectedBurnShares = lenderCommitmentGroupV3.previewWithdraw(withdrawAmount); + + vm.warp(1e6); // Advance time to satisfy withdraw delay + + vm.prank(address(lender)); + uint256 actualBurnShares = lenderCommitmentGroupV3.withdraw( + withdrawAmount, + address(lender), + address(lender) + ); + + assertEq(actualBurnShares, expectedBurnShares, "Actual withdraw shares burned should match preview"); + + // Test redeem preview matches actual redeem + uint256 redeemShares = 200000; + uint256 expectedRedeemAssets = lenderCommitmentGroupV3.previewRedeem(redeemShares); + + vm.warp(1e7); // Advance time to satisfy withdraw delay + + vm.prank(address(lender)); + uint256 actualRedeemAssets = lenderCommitmentGroupV3.redeem( + redeemShares, + address(lender), + address(lender) + ); + + assertEq(actualRedeemAssets, expectedRedeemAssets, "Actual redeem assets should match preview"); + } + + // ============ Pool Utilization & Interest Rate Tests ============ + + function test_getPoolUtilizationRatio() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensLended(500000); + + // 500000 / 1000000 = 50% = 5000 + uint16 ratio = lenderCommitmentGroupV3.getPoolUtilizationRatio(0); + assertEq(ratio, 5000, "Utilization ratio should be 50%"); + } + + function test_getPoolUtilizationRatio_with_delta() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensLended(500000); + + // (500000 + 250000) / 1000000 = 75% = 7500 + uint16 ratio = lenderCommitmentGroupV3.getPoolUtilizationRatio(250000); + assertEq(ratio, 7500, "Utilization ratio should be 75%"); + } + + function test_getPoolUtilizationRatio_capped_at_100() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensLended(1500000); + + uint16 ratio = lenderCommitmentGroupV3.getPoolUtilizationRatio(0); + assertEq(ratio, 10000, "Utilization ratio should be capped at 100%"); + } + + function test_getMinInterestRate() public { + initialize_group_contract(); + + // At 0% utilization, min rate = lowerBound (0) + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + uint16 rate = lenderCommitmentGroupV3.getMinInterestRate(0); + assertEq(rate, 0, "Min rate at 0% util should be lowerBound"); + } + + // ============ Principal Available to Borrow Tests ============ + + function test_getPrincipalAmountAvailableToBorrow() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + + uint256 available = lenderCommitmentGroupV3.getPrincipalAmountAvailableToBorrow(); + // liquidityThresholdPercent = 10000 (100%), so all committed is available + assertEq(available, 1000000, "All committed principal should be available"); + } + + function test_getPrincipalAmountAvailableToBorrow_with_loans() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensLended(600000); + + uint256 available = lenderCommitmentGroupV3.getPrincipalAmountAvailableToBorrow(); + assertEq(available, 400000, "Available should be committed minus lended"); + } + + function test_getPrincipalAmountAvailableToBorrow_threshold_reached() public { + initialize_group_contract(); + + lenderCommitmentGroupV3.set_totalPrincipalTokensCommitted(1000000); + lenderCommitmentGroupV3.set_totalPrincipalTokensLended(1000000); + + uint256 available = lenderCommitmentGroupV3.getPrincipalAmountAvailableToBorrow(); + assertEq(available, 0, "Nothing should be available when fully utilized"); + } + + // ============ Price Adapter Integration Tests ============ + + function test_calculateCollateralTokensAmountEquivalentToPrincipalTokens() public { + initialize_group_contract(); + + // With Q96 price (1:1), 1000 principal should need 1000 collateral + _mockPriceAdapter.setMockPriceRatioQ96(Q96); + + uint256 collateralNeeded = lenderCommitmentGroupV3.calculateCollateralTokensAmountEquivalentToPrincipalTokens(1000); + assertEq(collateralNeeded, 1000, "1:1 price should require equal collateral"); + } + + function test_calculateCollateralRequiredToBorrowPrincipal() public { + initialize_group_contract(); + + // collateralRatio = 10000 (100%), price is 1:1 + _mockPriceAdapter.setMockPriceRatioQ96(Q96); + + uint256 required = lenderCommitmentGroupV3.calculateCollateralRequiredToBorrowPrincipal(1000); + // With 100% collateral ratio, required = baseAmount * 100% = 1000 + assertEq(required, 1000, "With 100% ratio and 1:1 price, should need equal collateral"); + } + + function test_calculateCollateralTokensAmount_with_different_price() public { + initialize_group_contract(); + + // Set price to 2:1 (1 collateral = 2 principal), so Q96 * 2 + _mockPriceAdapter.setMockPriceRatioQ96(Q96 * 2); + + uint256 collateralNeeded = lenderCommitmentGroupV3.calculateCollateralTokensAmountEquivalentToPrincipalTokens(1000); + // With 2:1 price, 1000 principal needs 500 collateral + assertEq(collateralNeeded, 500, "2:1 price should require half collateral"); + } + + // ============ Getters / Interface Tests ============ + + function test_getCollateralTokenAddress() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.getCollateralTokenAddress(), address(collateralToken)); + } + + function test_getPrincipalTokenAddress() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.getPrincipalTokenAddress(), address(principalToken)); + } + + function test_getMarketId() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.getMarketId(), 1); + } + + function test_getMaxLoanDuration() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.getMaxLoanDuration(), 5000000); + } + + function test_asset() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.asset(), address(principalToken)); + } + + function test_getTokenDifferenceFromLiquidations() public { + initialize_group_contract(); + assertEq(lenderCommitmentGroupV3.getTokenDifferenceFromLiquidations(), 0); + + lenderCommitmentGroupV3.set_tokenDifferenceFromLiquidations(-5000); + assertEq(lenderCommitmentGroupV3.getTokenDifferenceFromLiquidations(), -5000); + } + + // ============ Max Deposit/Mint/Withdraw/Redeem Tests ============ + + function test_maxDeposit_returns_zero_when_paused() public { + initialize_group_contract(); + lenderCommitmentGroupV3.force_set_firstDepositMade(true); + + _protocolPausingManager.addPauser(address(_tellerV2)); + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pausePool(); + + uint256 maxDep = lenderCommitmentGroupV3.maxDeposit(address(lender)); + assertEq(maxDep, 0, "maxDeposit should be 0 when paused"); + } + + function test_maxDeposit_returns_zero_before_first_deposit_for_non_owner() public { + initialize_group_contract(); + // firstDepositMade is false + + vm.prank(address(lender)); + uint256 maxDep = lenderCommitmentGroupV3.maxDeposit(address(lender)); + assertEq(maxDep, 0, "maxDeposit should be 0 before first deposit for non-owner"); + } + + function test_maxWithdraw_returns_zero_when_paused() public { + initialize_group_contract(); + + _protocolPausingManager.addPauser(address(_tellerV2)); + vm.prank(address(_tellerV2)); + lenderCommitmentGroupV3.pausePool(); + + uint256 maxWith = lenderCommitmentGroupV3.maxWithdraw(address(lender)); + assertEq(maxWith, 0, "maxWithdraw should be 0 when paused"); + } + + function test_maxRedeem_returns_zero_within_delay() public { + initialize_group_contract(); + + vm.warp(1000); + + vm.prank(address(lenderCommitmentGroupV3)); + lenderCommitmentGroupV3.force_mint_shares(address(lender), 1000000); + + // Don't warp past delay + uint256 maxRed = lenderCommitmentGroupV3.maxRedeem(address(lender)); + assertEq(maxRed, 0, "maxRedeem should be 0 within withdraw delay"); + } +} diff --git a/packages/contracts/tests_fork/ApeChain_PoolsV3_Test.sol b/packages/contracts/tests_fork/ApeChain_PoolsV3_Test.sol new file mode 100644 index 000000000..b9d00d53f --- /dev/null +++ b/packages/contracts/tests_fork/ApeChain_PoolsV3_Test.sol @@ -0,0 +1,245 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; +import "forge-std/StdJson.sol"; + +import { LenderCommitmentGroup_Pool_V3 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol"; +import { LenderCommitmentGroupFactory_V3 } from "../contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol"; +import { ILenderCommitmentGroup_V3 } from "../contracts/interfaces/ILenderCommitmentGroup_V3.sol"; +import { PriceAdapterAlgebra } from "../contracts/price_adapters/PriceAdapterAlgebra.sol"; + +import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; + +/** + * @title ApeChain Pool V3 Fork Test + * @notice End-to-end test of Pool V3 + PriceAdapterAlgebra + Camelot V3. + * + * Proves that Blocker #1 (Algebra oracle incompatibility) is resolved: + * Pool V3 → IPriceAdapter → PriceAdapterAlgebra → globalState()/getTimepoints() → Camelot V3 + */ + +interface IERC20_APE { + function balanceOf(address account) external view returns (uint256); + function approve(address spender, uint256 amount) external returns (bool); + function symbol() external view returns (string memory); + function decimals() external view returns (uint8); + function transfer(address to, uint256 amount) external returns (bool); +} + +interface IAlgebraFactory { + function poolByPair(address tokenA, address tokenB) external view returns (address pool); +} + +interface IAlgebraPool_V3Test { + function token0() external view returns (address); + function token1() external view returns (address); + function globalState() external view returns ( + uint160 price, int24 tick, uint16 feeZto, uint16 feeOtz, + uint16 timepointIndex, uint8 communityFeeToken0, + uint8 communityFeeToken1, bool unlocked + ); +} + +interface IMarketRegistry_V3 { + function createMarket( + address _initialOwner, uint32 _paymentCycleDuration, + uint32 _paymentDefaultDuration, uint32 _bidExpirationTime, + uint16 _feePercent, bool _requireLenderAttestation, + bool _requireBorrowerAttestation, string calldata _uri + ) external returns (uint256 marketId_); +} + +interface ITellerV2_V3 { + function marketRegistry() external view returns (address); + function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; + function approveMarketForwarder(uint256 _marketId, address _forwarder) external; +} + +interface IERC4626_Simple { + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + function totalAssets() external view returns (uint256); + function totalSupply() external view returns (uint256); + function balanceOf(address account) external view returns (uint256); +} + +contract ApeChain_PoolsV3_Fork_Test is Test { + + string constant NETWORK_NAME = "apechain"; + + address constant CAMELOT_V3_FACTORY = 0x10aA510d94E094Bd643677bd2964c3EE085Daffc; + address constant WAPE = 0x48b62137EdfA95a428D35C09E44256a739F6B557; + address constant ApeUSD = 0xA2235d059F80e176D931Ef76b6C51953Eb3fBEf4; + + ITellerV2_V3 tellerV2; + IMarketRegistry_V3 marketRegistry; + address smartCommitmentForwarder; + + PriceAdapterAlgebra priceAdapter; + LenderCommitmentGroupFactory_V3 factoryV3; + address beaconAddress; + + uint256 marketId; + + address camelotPool; + bool zeroForOne; + uint8 apeUsdDecimals; + uint8 wapeDecimals; + + using stdJson for string; + + function getDeployedAddress(string memory contractName) internal view returns (address) { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/deployments/", NETWORK_NAME, "/", contractName, ".json"); + string memory json = vm.readFile(path); + return json.readAddress(".address"); + } + + function setUp() public { + // Load already-deployed TellerV2 and SmartCommitmentForwarder + tellerV2 = ITellerV2_V3(getDeployedAddress("TellerV2")); + smartCommitmentForwarder = getDeployedAddress("SmartCommitmentForwarder"); + marketRegistry = IMarketRegistry_V3(tellerV2.marketRegistry()); + + assertTrue(address(tellerV2).code.length > 0, "TellerV2 not found"); + assertTrue(smartCommitmentForwarder.code.length > 0, "SCF not found"); + + // Deploy PriceAdapterAlgebra fresh + priceAdapter = new PriceAdapterAlgebra(); + + // Deploy Pool V3 implementation + LenderCommitmentGroup_Pool_V3 poolImpl = new LenderCommitmentGroup_Pool_V3( + address(tellerV2), + smartCommitmentForwarder + ); + + // Deploy UpgradeableBeacon + UpgradeableBeacon beacon = new UpgradeableBeacon(address(poolImpl)); + beaconAddress = address(beacon); + + // Deploy Factory V3 (use a minimal proxy pattern — deploy and initialize) + factoryV3 = new LenderCommitmentGroupFactory_V3(); + factoryV3.initialize(beaconAddress); + + // Create market and set trusted forwarder + marketId = marketRegistry.createMarket( + address(this), 2592000, 2592000, 86400, 0, false, false, "" + ); + tellerV2.setTrustedMarketForwarder(marketId, smartCommitmentForwarder); + + // Look up Camelot V3 WAPE/ApeUSD pool + camelotPool = IAlgebraFactory(CAMELOT_V3_FACTORY).poolByPair(WAPE, ApeUSD); + require(camelotPool != address(0), "No WAPE/ApeUSD Camelot pool"); + + IAlgebraPool_V3Test pool = IAlgebraPool_V3Test(camelotPool); + zeroForOne = (pool.token0() == ApeUSD); + apeUsdDecimals = IERC20_APE(ApeUSD).decimals(); + wapeDecimals = IERC20_APE(WAPE).decimals(); + } + + // ============ Helpers ============ + + function _getApeUSD(address to, uint256 amount) internal { + vm.prank(camelotPool); + IERC20_APE(ApeUSD).transfer(to, amount); + } + + function _buildPriceAdapterRoute() internal view returns (bytes memory) { + IAlgebraPool_V3Test pool = IAlgebraPool_V3Test(camelotPool); + + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](1); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: zeroForOne, + twapInterval: 5, + token0Decimals: pool.token0() == ApeUSD ? apeUsdDecimals : wapeDecimals, + token1Decimals: pool.token1() == ApeUSD ? apeUsdDecimals : wapeDecimals + }); + + return priceAdapter.encodePoolRoutes(routes); + } + + function _deployPoolV3(uint256 initialDeposit) internal returns (address) { + ILenderCommitmentGroup_V3.CommitmentGroupConfig memory config = ILenderCommitmentGroup_V3.CommitmentGroupConfig({ + principalTokenAddress: ApeUSD, + collateralTokenAddress: WAPE, + marketId: marketId, + maxLoanDuration: 604800, + interestRateLowerBound: 6000, + interestRateUpperBound: 11000, + liquidityThresholdPercent: 8000, + collateralRatio: 15000 + }); + + bytes memory route = _buildPriceAdapterRoute(); + + _getApeUSD(address(this), initialDeposit); + IERC20_APE(ApeUSD).approve(address(factoryV3), initialDeposit); + + return factoryV3.deployLenderCommitmentGroupPool( + initialDeposit, + config, + address(priceAdapter), + route + ); + } + + // ============ Tests ============ + + /// @notice PriceAdapterAlgebra can register route and return a nonzero price + function test_priceAdapterAlgebra_works() public { + bytes memory route = _buildPriceAdapterRoute(); + bytes32 routeHash = priceAdapter.registerPriceRoute(route); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertGt(priceRatioQ96, 0, "Price ratio should be nonzero"); + + console.log("PriceAdapterAlgebra priceRatioQ96:", priceRatioQ96); + console.log("Route hash:", uint256(routeHash)); + } + + /// @notice Deploy pool via Factory V3 with PriceAdapterAlgebra + initial deposit + function test_deployPool_succeeds() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPoolV3(initialDeposit); + + assertTrue(pool != address(0), "Pool should be deployed"); + assertTrue(pool.code.length > 0, "Pool should have code"); + + console.log("Pool V3 deployed:", pool); + console.log("Pool totalAssets:", IERC4626_Simple(pool).totalAssets()); + console.log("Pool totalSupply:", IERC4626_Simple(pool).totalSupply()); + } + + /// @notice Full pricing path: Pool V3 -> IPriceAdapter -> PriceAdapterAlgebra -> Camelot V3 + function test_pool_collateralCalculation_works() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPoolV3(initialDeposit); + + LenderCommitmentGroup_Pool_V3 poolV3 = LenderCommitmentGroup_Pool_V3(payable(pool)); + + uint256 principalAmount = 10 * 10**apeUsdDecimals; + uint256 collateralNeeded = poolV3.calculateCollateralTokensAmountEquivalentToPrincipalTokens(principalAmount); + + assertGt(collateralNeeded, 0, "Collateral calculation should be nonzero"); + + console.log("Principal amount:", principalAmount); + console.log("Collateral needed:", collateralNeeded); + console.log("Full pricing path works: Pool V3 -> IPriceAdapter -> PriceAdapterAlgebra -> Camelot V3"); + } + + /// @notice Pool reports available liquidity after initial deposit + function test_pool_getPrincipalAvailableToBorrow() public { + uint256 initialDeposit = 100 * 10**apeUsdDecimals; + address pool = _deployPoolV3(initialDeposit); + + LenderCommitmentGroup_Pool_V3 poolV3 = LenderCommitmentGroup_Pool_V3(payable(pool)); + + uint256 available = poolV3.getPrincipalAmountAvailableToBorrow(); + assertGt(available, 0, "Pool should have liquidity available"); + + console.log("Available to borrow:", available); + console.log("Total assets:", IERC4626_Simple(pool).totalAssets()); + } +} diff --git a/packages/contracts/tests_fork/PriceAdapterAlgebra_Test.sol b/packages/contracts/tests_fork/PriceAdapterAlgebra_Test.sol new file mode 100644 index 000000000..6121915c9 --- /dev/null +++ b/packages/contracts/tests_fork/PriceAdapterAlgebra_Test.sol @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import { Test } from "../tests/util/FoundryTest.sol"; +import "forge-std/console.sol"; + +import { PriceAdapterAlgebra } from "../contracts/price_adapters/PriceAdapterAlgebra.sol"; +import { IAlgebraPool } from "../contracts/interfaces/defi/IAlgebraPool.sol"; + +interface IAlgebraFactory { + function poolByPair(address tokenA, address tokenB) external view returns (address pool); +} + +interface IERC20Minimal { + function decimals() external view returns (uint8); + function symbol() external view returns (string memory); +} + +/** + * @title PriceAdapterAlgebra_Test + * @notice Fork test for PriceAdapterAlgebra against ApeChain Camelot V3 (Algebra) pool. + * @dev Run with: forge test --match-contract PriceAdapterAlgebra -vv --fork-url + */ +contract PriceAdapterAlgebra_Test is Test { + + address constant CAMELOT_V3_FACTORY = 0x10aA510d94E094Bd643677bd2964c3EE085Daffc; + address constant WAPE = 0x48b62137EdfA95a428D35C09E44256a739F6B557; + address constant ApeUSD = 0xA2235d059F80e176D931Ef76b6C51953Eb3fBEf4; + + PriceAdapterAlgebra public priceAdapter; + address public camelotPool; + + address token0; + address token1; + uint8 token0Decimals; + uint8 token1Decimals; + + function setUp() public { + priceAdapter = new PriceAdapterAlgebra(); + + camelotPool = IAlgebraFactory(CAMELOT_V3_FACTORY).poolByPair(WAPE, ApeUSD); + require(camelotPool != address(0), "No WAPE/ApeUSD Camelot pool"); + assertTrue(camelotPool.code.length > 0, "Pool should have code"); + + IAlgebraPool pool = IAlgebraPool(camelotPool); + token0 = pool.token0(); + token1 = pool.token1(); + token0Decimals = IERC20Minimal(token0).decimals(); + token1Decimals = IERC20Minimal(token1).decimals(); + + console.log("Pool address:", camelotPool); + console.log("Token0:", token0, IERC20Minimal(token0).symbol()); + console.log("Token1:", token1, IERC20Minimal(token1).symbol()); + } + + // ============ Route Registration ============ + + function test_register_price_route() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](1); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + bytes memory storedRoute = priceAdapter.priceRoutes(routeHash); + assertEq(storedRoute.length, encodedRoute.length, "Route should be stored"); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "Price should be nonzero"); + console.log("Route registered, priceRatioQ96:", priceRatioQ96); + } + + // ============ Spot Price (globalState) ============ + + function test_spot_price_token0_to_token1() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](1); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 0, // spot price via globalState() + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "Spot price should be > 0"); + + uint256 priceScaled = (priceRatioQ96 * 1e18) / (2 ** 96); + console.log("Spot price (token0->token1) Q96:", priceRatioQ96); + console.log("Spot price (scaled 1e18):", priceScaled); + } + + function test_spot_price_token1_to_token0() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](1); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: false, // inverse + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "Inverse spot price should be > 0"); + + uint256 priceScaled = (priceRatioQ96 * 1e18) / (2 ** 96); + console.log("Spot price (token1->token0) Q96:", priceRatioQ96); + console.log("Spot price (scaled 1e18):", priceScaled); + } + + // ============ TWAP Price (getTimepoints) ============ + + function test_twap_price() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](1); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 5, // 5 second TWAP via getTimepoints() + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "TWAP price should be > 0"); + + uint256 priceScaled = (priceRatioQ96 * 1e18) / (2 ** 96); + console.log("TWAP price Q96:", priceRatioQ96); + console.log("TWAP price (scaled 1e18):", priceScaled); + } + + function test_compare_spot_vs_twap() public { + // Spot + PriceAdapterAlgebra.PoolRoute[] memory spotRoutes = new PriceAdapterAlgebra.PoolRoute[](1); + spotRoutes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + bytes32 spotHash = priceAdapter.registerPriceRoute(priceAdapter.encodePoolRoutes(spotRoutes)); + uint256 spotPrice = priceAdapter.getPriceRatioQ96(spotHash); + + // TWAP + PriceAdapterAlgebra.PoolRoute[] memory twapRoutes = new PriceAdapterAlgebra.PoolRoute[](1); + twapRoutes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 5, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + bytes32 twapHash = priceAdapter.registerPriceRoute(priceAdapter.encodePoolRoutes(twapRoutes)); + uint256 twapPrice = priceAdapter.getPriceRatioQ96(twapHash); + + assertTrue(spotPrice > 0, "Spot price should be positive"); + assertTrue(twapPrice > 0, "TWAP price should be positive"); + + uint256 diff = spotPrice > twapPrice ? spotPrice - twapPrice : twapPrice - spotPrice; + uint256 percentDiff = (diff * 100) / spotPrice; + + console.log("Spot price Q96:", spotPrice); + console.log("TWAP price Q96:", twapPrice); + console.log("Difference:", percentDiff, "%"); + } + + // ============ Multi-hop ============ + + function test_two_hop_route() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](2); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: false, // go back + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "Two-hop price should be > 0"); + + uint256 priceScaled = (priceRatioQ96 * 1e18) / (2 ** 96); + console.log("Two-hop Price Q96:", priceRatioQ96); + console.log("Two-hop Price (scaled 1e18):", priceScaled); + console.log("Expected ~1e18 (roundtrip should be ~1.0)"); + } + + function test_two_hop_route_twap() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](2); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 5, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: false, + twapInterval: 5, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + + bytes memory encodedRoute = priceAdapter.encodePoolRoutes(routes); + bytes32 routeHash = priceAdapter.registerPriceRoute(encodedRoute); + + uint256 priceRatioQ96 = priceAdapter.getPriceRatioQ96(routeHash); + assertTrue(priceRatioQ96 > 0, "Two-hop TWAP price should be > 0"); + + uint256 priceScaled = (priceRatioQ96 * 1e18) / (2 ** 96); + console.log("Two-hop TWAP Price Q96:", priceRatioQ96); + console.log("Two-hop TWAP Price (scaled 1e18):", priceScaled); + } + + // ============ Edge Cases ============ + + function test_decode_rejects_invalid_route_length() public { + PriceAdapterAlgebra.PoolRoute[] memory routes = new PriceAdapterAlgebra.PoolRoute[](3); + routes[0] = PriceAdapterAlgebra.PoolRoute({ + pool: camelotPool, + zeroForOne: true, + twapInterval: 0, + token0Decimals: token0Decimals, + token1Decimals: token1Decimals + }); + routes[1] = routes[0]; + routes[2] = routes[0]; + + bytes memory encodedRoute = abi.encode(routes); + + vm.expectRevert("Route must have 1 or 2 pools"); + priceAdapter.decodePoolRoutes(encodedRoute); + } + + function test_get_price_reverts_for_unregistered_route() public { + bytes32 fakeRouteHash = keccak256("fake route"); + + vm.expectRevert("Route not found"); + priceAdapter.getPriceRatioQ96(fakeRouteHash); + } +} From f5e9bb65ea6e73646acc4401518c5a7465a42409 Mon Sep 17 00:00:00 2001 From: Ethereumdegen Date: Thu, 26 Feb 2026 22:30:31 -0500 Subject: [PATCH 44/46] deployed poolsv3 --- .../.openzeppelin/unknown-33139.json | 511 + .../deployments/apechain/.migrations.json | 4 +- .../deployments/apechain/FixedPointQ96.json | 134 + .../LenderCommitmentGroupBeaconV3.json | 1893 +++ .../LenderCommitmentGroupFactory_V3.json | 200 + .../apechain/PriceAdapterAlgebra.json | 239 + .../3b875778126b5c8a21485ac9e3e615af.json | 1002 ++ packages/contracts/package.json | 2 +- packages/subgraph-pool/package.json | 2 +- packages/subgraph/package.json | 4 +- yarn.lock | 14133 +++++----------- 11 files changed, 8688 insertions(+), 9436 deletions(-) create mode 100644 packages/contracts/deployments/apechain/FixedPointQ96.json create mode 100644 packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV3.json create mode 100644 packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V3.json create mode 100644 packages/contracts/deployments/apechain/PriceAdapterAlgebra.json create mode 100644 packages/contracts/deployments/apechain/solcInputs/3b875778126b5c8a21485ac9e3e615af.json diff --git a/packages/contracts/.openzeppelin/unknown-33139.json b/packages/contracts/.openzeppelin/unknown-33139.json index 1cf679c31..706c9f00a 100644 --- a/packages/contracts/.openzeppelin/unknown-33139.json +++ b/packages/contracts/.openzeppelin/unknown-33139.json @@ -74,6 +74,11 @@ "address": "0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D", "txHash": "0xdfdd739a69e9844c0c8a1e751478e43df55a5cf6003f17c973c994c1e6d87666", "kind": "transparent" + }, + { + "address": "0x26E2BD4F67136a7929DFE82BD6392633eb5610C2", + "txHash": "0x2d54c82c51dad7665114f75baf01956cdcb78f73c1e1c5bdaaf8ba592f57cc43", + "kind": "transparent" } ], "impls": { @@ -3197,6 +3202,512 @@ }, "namespaces": {} } + }, + "bfaf5a2b57843f073d47a339146e3598a880cf725fb192d245c2603bcd7911cb": { + "address": "0x688d3d7D900f38ce095914608AD069d5AA2331DB", + "txHash": "0x83276a39d9fb7490638114981f9b9a1901c1319c29ce30ea10cd71bd1480616c", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "_status", + "offset": 0, + "slot": "101", + "type": "t_uint256", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:38" + }, + { + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage", + "contract": "ReentrancyGuardUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol:80" + }, + { + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:37" + }, + { + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:39" + }, + { + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:41" + }, + { + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:43" + }, + { + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44" + }, + { + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage", + "contract": "ERC20Upgradeable", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:400" + }, + { + "label": "poolSharesLastTransferredAt", + "offset": 0, + "slot": "201", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:31" + }, + { + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)50_storage", + "contract": "LenderCommitmentGroupSharesIntegrated", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol:123" + }, + { + "label": "priceAdapter", + "offset": 0, + "slot": "252", + "type": "t_address", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:116" + }, + { + "label": "principalToken", + "offset": 0, + "slot": "253", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:120" + }, + { + "label": "collateralToken", + "offset": 0, + "slot": "254", + "type": "t_contract(IERC20)8314", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:121" + }, + { + "label": "marketId", + "offset": 0, + "slot": "255", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:123" + }, + { + "label": "totalPrincipalTokensCommitted", + "offset": 0, + "slot": "256", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:126" + }, + { + "label": "totalPrincipalTokensWithdrawn", + "offset": 0, + "slot": "257", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:127" + }, + { + "label": "totalPrincipalTokensLended", + "offset": 0, + "slot": "258", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:129" + }, + { + "label": "totalPrincipalTokensRepaid", + "offset": 0, + "slot": "259", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:130" + }, + { + "label": "excessivePrincipalTokensRepaid", + "offset": 0, + "slot": "260", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:131" + }, + { + "label": "totalInterestCollected", + "offset": 0, + "slot": "261", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:133" + }, + { + "label": "liquidityThresholdPercent", + "offset": 0, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:135" + }, + { + "label": "collateralRatio", + "offset": 2, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:136" + }, + { + "label": "maxLoanDuration", + "offset": 4, + "slot": "262", + "type": "t_uint32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:138" + }, + { + "label": "interestRateLowerBound", + "offset": 8, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:139" + }, + { + "label": "interestRateUpperBound", + "offset": 10, + "slot": "262", + "type": "t_uint16", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:140" + }, + { + "label": "activeBids", + "offset": 0, + "slot": "263", + "type": "t_mapping(t_uint256,t_bool)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:148" + }, + { + "label": "activeBidsAmountDueRemaining", + "offset": 0, + "slot": "264", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:149" + }, + { + "label": "tokenDifferenceFromLiquidations", + "offset": 0, + "slot": "265", + "type": "t_int256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:151" + }, + { + "label": "firstDepositMade", + "offset": 0, + "slot": "266", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:153" + }, + { + "label": "withdrawDelayTimeSeconds", + "offset": 0, + "slot": "267", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:154" + }, + { + "label": "priceRouteHash", + "offset": 0, + "slot": "268", + "type": "t_bytes32", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:158" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "offset": 0, + "slot": "269", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:162" + }, + { + "label": "lastUnpausedAt", + "offset": 0, + "slot": "270", + "type": "t_uint256", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:165" + }, + { + "label": "paused", + "offset": 0, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:166" + }, + { + "label": "borrowingPaused", + "offset": 1, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:167" + }, + { + "label": "liquidationAuctionPaused", + "offset": 2, + "slot": "271", + "type": "t_bool", + "contract": "LenderCommitmentGroup_Pool_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.sol:168" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)45_storage": { + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "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_contract(IERC20)8314": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_int256": { + "label": "int256", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_bool)": { + "label": "mapping(uint256 => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "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": {} + } + }, + "e7600012e4799239612d0e1f3144fda1c1338a0e279c721300f5abbfd264fa7c": { + "address": "0xbD9B31A1a52340813F0191b869C8CC919990613E", + "txHash": "0xe99c341db7f7f6c272d0b460875142359f979c8bc4d19d59bb96060e8ab53931", + "layout": { + "solcVersion": "0.8.24", + "storage": [ + { + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:22" + }, + { + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage", + "contract": "OwnableUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:94" + }, + { + "label": "lenderGroupBeacon", + "offset": 0, + "slot": "101", + "type": "t_address", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:32" + }, + { + "label": "deployedLenderGroupContracts", + "offset": 0, + "slot": "102", + "type": "t_mapping(t_address,t_uint256)", + "contract": "LenderCommitmentGroupFactory_V3", + "src": "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol:36" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "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_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } } } } diff --git a/packages/contracts/deployments/apechain/.migrations.json b/packages/contracts/deployments/apechain/.migrations.json index fbbbfab64..404bf10c6 100644 --- a/packages/contracts/deployments/apechain/.migrations.json +++ b/packages/contracts/deployments/apechain/.migrations.json @@ -23,5 +23,7 @@ "apechain:transfer-ownership-to-safe": 1771555559, "validate-deployments": 1771555560, "default-proxy-admin:transfer": 1771555560, - "apechain:transfer-timelock-ownership": 1771556073 + "apechain:transfer-timelock-ownership": 1771556073, + "lender-commitment-group-beacon-v3:deploy": 1772162877, + "lender-commitment-group-factory-v3:deploy": 1772162931 } \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/FixedPointQ96.json b/packages/contracts/deployments/apechain/FixedPointQ96.json new file mode 100644 index 000000000..7d4b3864f --- /dev/null +++ b/packages/contracts/deployments/apechain/FixedPointQ96.json @@ -0,0 +1,134 @@ +{ + "address": "0xE00384587DC733D1E201e1EAa5583645d351C01C", + "abi": [ + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "divideFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "q96Value", + "type": "uint256" + } + ], + "name": "fromFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "fixedPointA", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "fixedPointB", + "type": "uint256" + } + ], + "name": "multiplyFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "numerator", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "denominator", + "type": "uint256" + } + ], + "name": "toFixedPoint96", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "pure", + "type": "function" + } + ], + "transactionHash": "0xd6491a6bf5e46bfbe4299f54b9f6c0488bc9c5703cb2ddb1cf67e40416f99cfd", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0xE00384587DC733D1E201e1EAa5583645d351C01C", + "transactionIndex": 1, + "gasUsed": "144747", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xf7896ff097ba599a083950669334dc160b6b13aec1f230727eabb0e5ecd0c4a5", + "transactionHash": "0xd6491a6bf5e46bfbe4299f54b9f6c0488bc9c5703cb2ddb1cf67e40416f99cfd", + "logs": [], + "blockNumber": 34210301, + "cumulativeGasUsed": "144747", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "3b875778126b5c8a21485ac9e3e615af", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"divideFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"q96Value\",\"type\":\"uint256\"}],\"name\":\"fromFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"fixedPointA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"fixedPointB\",\"type\":\"uint256\"}],\"name\":\"multiplyFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numerator\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"denominator\",\"type\":\"uint256\"}],\"name\":\"toFixedPoint96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"title\":\"FixedPoint96\",\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"notice\":\"A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/FixedPointQ96.sol\":\"FixedPointQ96\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"}},\"version\":1}", + "bytecode": "0x6101a761003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100565760003560e01c80630f55b8251461005b57806312b28bda146100805780637038961414610093578063c9bcd4f414610080575b600080fd5b61006e6100693660046100ef565b6100a6565b60405190815260200160405180910390f35b61006e61008e366004610108565b6100bc565b61006e6100a1366004610108565b6100de565b60006100b6600160601b8361012a565b92915050565b6000816100cd600160601b8561014c565b6100d7919061012a565b9392505050565b6000600160601b6100cd838561014c565b60006020828403121561010157600080fd5b5035919050565b6000806040838503121561011b57600080fd5b50508035926020909101359150565b60008261014757634e487b7160e01b600052601260045260246000fd5b500490565b80820281158282048414176100b657634e487b7160e01b600052601160045260246000fdfea2646970667358221220e85f9c1371c56351fff758295a0d29103c4f10d442dd56d16a533e4b1dde4a5464736f6c63430008180033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100565760003560e01c80630f55b8251461005b57806312b28bda146100805780637038961414610093578063c9bcd4f414610080575b600080fd5b61006e6100693660046100ef565b6100a6565b60405190815260200160405180910390f35b61006e61008e366004610108565b6100bc565b61006e6100a1366004610108565b6100de565b60006100b6600160601b8361012a565b92915050565b6000816100cd600160601b8561014c565b6100d7919061012a565b9392505050565b6000600160601b6100cd838561014c565b60006020828403121561010157600080fd5b5035919050565b6000806040838503121561011b57600080fd5b50508035926020909101359150565b60008261014757634e487b7160e01b600052601260045260246000fd5b500490565b80820281158282048414176100b657634e487b7160e01b600052601160045260246000fdfea2646970667358221220e85f9c1371c56351fff758295a0d29103c4f10d442dd56d16a533e4b1dde4a5464736f6c63430008180033", + "devdoc": { + "kind": "dev", + "methods": {}, + "title": "FixedPoint96", + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "notice": "A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) ", + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV3.json b/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV3.json new file mode 100644 index 000000000..8c2a2f1ce --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderCommitmentGroupBeaconV3.json @@ -0,0 +1,1893 @@ +{ + "address": "0xa4A8c60Ac9E0c38f8B46316c6B3B508b3BA04415", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_smartCommitmentForwarder" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Approval", + "inputs": [ + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "address", + "name": "spender", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "BorrowerAcceptedFunds", + "inputs": [ + { + "type": "address", + "name": "borrower", + "indexed": true + }, + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "collateralAmount", + "indexed": false + }, + { + "type": "uint32", + "name": "loanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRate", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DefaultedLoanLiquidated", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "liquidator", + "indexed": true + }, + { + "type": "uint256", + "name": "amountDue", + "indexed": false + }, + { + "type": "int256", + "name": "tokenAmountDifference", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Deposit", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "LoanRepaid", + "inputs": [ + { + "type": "uint256", + "name": "bidId", + "indexed": true + }, + { + "type": "address", + "name": "repayer", + "indexed": true + }, + { + "type": "uint256", + "name": "principalAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "interestAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "totalPrincipalRepaid", + "indexed": false + }, + { + "type": "uint256", + "name": "totalInterestCollected", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Paused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "PoolInitialized", + "inputs": [ + { + "type": "address", + "name": "principalTokenAddress", + "indexed": true + }, + { + "type": "address", + "name": "collateralTokenAddress", + "indexed": true + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "uint32", + "name": "maxLoanDuration", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateLowerBound", + "indexed": false + }, + { + "type": "uint16", + "name": "interestRateUpperBound", + "indexed": false + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent", + "indexed": false + }, + { + "type": "uint16", + "name": "loanToValuePercent", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "SharesLastTransferredAt", + "inputs": [ + { + "type": "address", + "name": "recipient", + "indexed": true + }, + { + "type": "uint256", + "name": "transferredAt", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Transfer", + "inputs": [ + { + "type": "address", + "name": "from", + "indexed": true + }, + { + "type": "address", + "name": "to", + "indexed": true + }, + { + "type": "uint256", + "name": "value", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Unpaused", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedBorrowing", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UnpausedLiquidationAuction", + "inputs": [ + { + "type": "address", + "name": "account", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Withdraw", + "inputs": [ + { + "type": "address", + "name": "caller", + "indexed": true + }, + { + "type": "address", + "name": "receiver", + "indexed": true + }, + { + "type": "address", + "name": "owner", + "indexed": true + }, + { + "type": "uint256", + "name": "assets", + "indexed": false + }, + { + "type": "uint256", + "name": "shares", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "WithdrawFromEscrow", + "inputs": [ + { + "type": "uint256", + "name": "amount", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MAX_WITHDRAW_DELAY_TIME", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "MIN_TWAP_INTERVAL", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "ORACLE_MANAGER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "SMART_COMMITMENT_FORWARDER", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "TELLER_V2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "UNISWAP_EXPANSION_FACTOR", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptFundsForAcceptBid", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_borrower" + }, + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "uint16", + "name": "_interestRate" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "activeBids", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "activeBidsAmountDueRemaining", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "allowance", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + }, + { + "type": "address", + "name": "spender" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "approve", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "asset", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "assetTokenAddress" + } + ] + }, + { + "type": "function", + "name": "balanceOf", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "borrowingPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralRequiredToBorrowPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "principalAmount" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "collateralTokensAmountToMatchValue" + } + ] + }, + { + "type": "function", + "name": "collateralRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "collateralToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "convertToShares", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decimals", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "decreaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "subtractedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deposit", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "excessivePrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "firstDepositMade", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCollateralTokenType", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint8", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getLastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMaxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinInterestRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "amountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amountOwed" + }, + { + "type": "uint256", + "name": "_loanDefaultedTimestamp" + } + ], + "outputs": [ + { + "type": "int256", + "name": "amountDifference_" + } + ] + }, + { + "type": "function", + "name": "getPoolUtilizationRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "activeLoansAmountDelta" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalAmountAvailableToBorrow", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getSharesLastTransferredAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTokenDifferenceFromLiquidations", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "int256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "increaseAllowance", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "spender" + }, + { + "type": "uint256", + "name": "addedValue" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapter" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "interestRateLowerBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "interestRateUpperBound", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "lastUnpausedAt", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidateDefaultedLoanWithIncentive", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "int256", + "name": "_tokenAmountDifference" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "liquidationAuctionPaused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "liquidityThresholdPercent", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxLoanDuration", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxPrincipalPerCollateralAmount", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "maxWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "mint", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "name", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "pauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "pausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "paused", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewDeposit", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewMint", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewRedeem", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "previewWithdraw", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceAdapter", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "priceRouteHash", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "bytes32", + "name": "" + } + ] + }, + { + "type": "function", + "name": "principalToken", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "redeem", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "shares" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "assets" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "repayLoanCallback", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_bidId" + }, + { + "type": "address", + "name": "repayer" + }, + { + "type": "uint256", + "name": "principalAmount" + }, + { + "type": "uint256", + "name": "interestAmount" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "setWithdrawDelayTime", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_seconds" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "sharesExchangeRate", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "sharesExchangeRateInverse", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "rate_" + } + ] + }, + { + "type": "function", + "name": "symbol", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "string", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalAssets", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalInterestCollected", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensCommitted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensLended", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensRepaid", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalPrincipalTokensWithdrawn", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "totalSupply", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transfer", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferFrom", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "from" + }, + { + "type": "address", + "name": "to" + }, + { + "type": "uint256", + "name": "amount" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseBorrowing", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpauseLiquidationAuction", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "unpausePool", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "withdraw", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "assets" + }, + { + "type": "address", + "name": "receiver" + }, + { + "type": "address", + "name": "owner" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "shares" + } + ] + }, + { + "type": "function", + "name": "withdrawDelayTimeSeconds", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "withdrawFromEscrowVault", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_amount" + } + ], + "outputs": [] + } + ], + "receipt": {}, + "numDeployments": 1, + "implementation": "0x688d3d7D900f38ce095914608AD069d5AA2331DB" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V3.json b/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V3.json new file mode 100644 index 000000000..e49d1fac0 --- /dev/null +++ b/packages/contracts/deployments/apechain/LenderCommitmentGroupFactory_V3.json @@ -0,0 +1,200 @@ +{ + "address": "0x26E2BD4F67136a7929DFE82BD6392633eb5610C2", + "abi": [ + { + "type": "event", + "anonymous": false, + "name": "DeployedLenderGroupContract", + "inputs": [ + { + "type": "address", + "name": "groupContract", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "OwnershipTransferred", + "inputs": [ + { + "type": "address", + "name": "previousOwner", + "indexed": true + }, + { + "type": "address", + "name": "newOwner", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "deployLenderCommitmentGroupPool", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_initialPrincipalAmount" + }, + { + "type": "tuple", + "name": "_commitmentGroupConfig", + "components": [ + { + "type": "address", + "name": "principalTokenAddress" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "uint32", + "name": "maxLoanDuration" + }, + { + "type": "uint16", + "name": "interestRateLowerBound" + }, + { + "type": "uint16", + "name": "interestRateUpperBound" + }, + { + "type": "uint16", + "name": "liquidityThresholdPercent" + }, + { + "type": "uint16", + "name": "collateralRatio" + } + ] + }, + { + "type": "address", + "name": "_priceAdapterAddress" + }, + { + "type": "bytes", + "name": "_priceAdapterRoute" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "deployedLenderGroupContracts", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "initialize", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_lenderGroupBeacon" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "lenderGroupBeacon", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "owner", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "renounceOwnership", + "constant": false, + "payable": false, + "inputs": [], + "outputs": [] + }, + { + "type": "function", + "name": "transferOwnership", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "newOwner" + } + ], + "outputs": [] + } + ], + "transactionHash": "0x2d54c82c51dad7665114f75baf01956cdcb78f73c1e1c5bdaaf8ba592f57cc43", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": "0xb9b67dcb3425aa6aad3f919593b6bd96bebeda05a8b5c4e2e8cc3535d116a265", + "blockNumber": 34211523 + }, + "numDeployments": 1, + "implementation": "0xbD9B31A1a52340813F0191b869C8CC919990613E" +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/PriceAdapterAlgebra.json b/packages/contracts/deployments/apechain/PriceAdapterAlgebra.json new file mode 100644 index 000000000..da46173c1 --- /dev/null +++ b/packages/contracts/deployments/apechain/PriceAdapterAlgebra.json @@ -0,0 +1,239 @@ +{ + "address": "0x5896B1168C2558886Fa590a5F57667b88a012874", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + }, + { + "indexed": false, + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "RouteRegistered", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "decodePoolRoutes", + "outputs": [ + { + "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 PriceAdapterAlgebra.PoolRoute[]", + "name": "route_array", + "type": "tuple[]" + } + ], + "stateMutability": "pure", + "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 PriceAdapterAlgebra.PoolRoute[]", + "name": "routes", + "type": "tuple[]" + } + ], + "name": "encodePoolRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "encoded", + "type": "bytes" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "route", + "type": "bytes32" + } + ], + "name": "getPriceRatioQ96", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatioQ96", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "name": "priceRoutes", + "outputs": [ + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "bytes", + "name": "route", + "type": "bytes" + } + ], + "name": "registerPriceRoute", + "outputs": [ + { + "internalType": "bytes32", + "name": "hash", + "type": "bytes32" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x21f7ad49b0b5226295288ff754294a62218437509bcfd25b8e479ac5bb3d7bbe", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x5896B1168C2558886Fa590a5F57667b88a012874", + "transactionIndex": 1, + "gasUsed": "1276312", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xe16777a00cee54097e98693f41b41bcd838ee7a45c4b70805b9215e7d50836a6", + "transactionHash": "0x21f7ad49b0b5226295288ff754294a62218437509bcfd25b8e479ac5bb3d7bbe", + "logs": [], + "blockNumber": 34210302, + "cumulativeGasUsed": "1276312", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "3b875778126b5c8a21485ac9e3e615af", + "metadata": "{\"compiler\":{\"version\":\"0.8.24+commit.e11b9ed9\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"RouteRegistered\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"decodePoolRoutes\",\"outputs\":[{\"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 PriceAdapterAlgebra.PoolRoute[]\",\"name\":\"route_array\",\"type\":\"tuple[]\"}],\"stateMutability\":\"pure\",\"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 PriceAdapterAlgebra.PoolRoute[]\",\"name\":\"routes\",\"type\":\"tuple[]\"}],\"name\":\"encodePoolRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"encoded\",\"type\":\"bytes\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"route\",\"type\":\"bytes32\"}],\"name\":\"getPriceRatioQ96\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatioQ96\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"priceRoutes\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"route\",\"type\":\"bytes\"}],\"name\":\"registerPriceRoute\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/price_adapters/PriceAdapterAlgebra.sol\":\"PriceAdapterAlgebra\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/interfaces/IPriceAdapter.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IPriceAdapter {\\n \\n function registerPriceRoute(bytes memory route) external returns (bytes32);\\n\\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\\n}\\n\",\"keccak256\":\"0xfac0eb348a5ced9e5f5ef29dd93c273c613ebb25f80afc845be2f1b6530e7ffa\",\"license\":\"MIT\"},\"contracts/interfaces/defi/IAlgebraPool.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0\\npragma solidity ^0.8.0;\\n\\n/**\\n * @title IAlgebraPool\\n * @notice Interface for Algebra V1 pools (used by Camelot V3 on ApeChain).\\n * Algebra pools use globalState() and getTimepoints() instead of\\n * Uniswap V3's slot0() and observe().\\n */\\ninterface IAlgebraPool {\\n function token0() external view returns (address);\\n function token1() external view returns (address);\\n\\n function globalState() external view returns (\\n uint160 price,\\n int24 tick,\\n uint16 feeZto,\\n uint16 feeOtz,\\n uint16 timepointIndex,\\n uint8 communityFeeToken0,\\n uint8 communityFeeToken1,\\n bool unlocked\\n );\\n\\n function getTimepoints(uint32[] calldata secondsAgos) external view returns (\\n int56[] memory tickCumulatives,\\n uint160[] memory secondsPerLiquidityCumulatives\\n );\\n}\\n\",\"keccak256\":\"0x21b9def30f048a27a2844bcf1590192700bd050380c15b250c528987c07a48ff\",\"license\":\"AGPL-3.0\"},\"contracts/libraries/FixedPointQ96.sol\":{\"content\":\"\\n\\n\\n\\n//use mul div and make sure we round the proper way ! \\n\\n\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \\nlibrary FixedPointQ96 {\\n uint8 constant RESOLUTION = 96;\\n uint256 constant Q96 = 0x1000000000000000000000000;\\n\\n\\n\\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\\n // The number is scaled by Q96 to convert into fixed point format\\n return (numerator * Q96) / denominator;\\n }\\n\\n // Example: Multiply two fixed-point numbers\\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * fixedPointB) / Q96;\\n }\\n\\n // Example: Divide two fixed-point numbers\\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\\n return (fixedPointA * Q96) / fixedPointB;\\n }\\n\\n\\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\\n return q96Value / Q96;\\n }\\n\\n}\\n\",\"keccak256\":\"0x83be4025348bc6a4164c7ce3a54f55629da64952b561dd238081d49716061ad1\"},\"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\"},\"contracts/price_adapters/PriceAdapterAlgebra.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n// Interfaces\\nimport \\\"../interfaces/IPriceAdapter.sol\\\";\\nimport \\\"../interfaces/defi/IAlgebraPool.sol\\\";\\n\\nimport {FixedPointQ96} from \\\"../libraries/FixedPointQ96.sol\\\";\\nimport {FullMath} from \\\"../libraries/uniswap/FullMath.sol\\\";\\nimport {TickMath} from \\\"../libraries/uniswap/TickMath.sol\\\";\\n\\n/*\\n\\n Price adapter for Algebra V1 pools (Camelot V3 on ApeChain).\\n Uses globalState() instead of slot0() and getTimepoints() instead of observe().\\n\\n*/\\n\\ncontract PriceAdapterAlgebra is IPriceAdapter {\\n\\n struct PoolRoute {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n }\\n\\n mapping(bytes32 => bytes) public priceRoutes;\\n\\n /* Events */\\n\\n event RouteRegistered(bytes32 hash, bytes route);\\n\\n /* External Functions */\\n\\n function registerPriceRoute(\\n bytes memory route\\n ) external returns (bytes32 hash) {\\n\\n PoolRoute[] memory route_array = decodePoolRoutes( route );\\n\\n require( route_array.length ==1 || route_array.length ==2, \\\"invalid route length\\\" );\\n\\n \\t\\t// hash the route with keccak256\\n bytes32 poolRouteHash = keccak256(route);\\n\\n \\t\\t// store the route by its hash in the priceRoutes mapping\\n priceRoutes[poolRouteHash] = route;\\n\\n emit RouteRegistered(poolRouteHash, route);\\n\\n return poolRouteHash;\\n }\\n\\n function getPriceRatioQ96(\\n bytes32 route\\n ) external view returns ( uint256 priceRatioQ96 ) {\\n\\n // lookup the route from the mapping\\n bytes memory routeData = priceRoutes[route];\\n require(routeData.length > 0, \\\"Route not found\\\");\\n\\n // decode the route\\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\\n\\n // start with Q96 = 1.0 in Q96 format\\n priceRatioQ96 = FixedPointQ96.Q96;\\n\\n // iterate through each pool and multiply prices\\n for (uint256 i = 0; i < poolRoutes.length; i++) {\\n uint256 poolPriceQ96 = getAlgebraPriceRatioForPool(poolRoutes[i]);\\n // multiply using Q96 arithmetic\\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\\n }\\n }\\n\\n // -------\\n\\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\\n\\n encoded = abi.encode(routes);\\n\\n }\\n\\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\\n\\n route_array = abi.decode(data, (PoolRoute[]));\\n\\n require(route_array.length == 1 || route_array.length == 2, \\\"Route must have 1 or 2 pools\\\");\\n\\n }\\n\\n // -------\\n\\n function getAlgebraPriceRatioForPool(\\n PoolRoute memory _poolRoute\\n ) internal view returns (uint256 priceRatioQ96) {\\n\\n // this is expanded by 2**96\\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRoute.pool,\\n _poolRoute.twapInterval\\n );\\n\\n // Convert sqrtPriceX96 to priceQ96\\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\\n\\n // If we need the inverse (token0 in terms of token1), invert\\n bool invert = !_poolRoute.zeroForOne;\\n if (invert) {\\n // To invert a Q96 number: (Q96 * Q96) / value\\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\\n }\\n }\\n\\n function getSqrtTwapX96(address algebraPool, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n if (twapInterval == 0) {\\n // return the current price from globalState (Algebra equivalent of slot0)\\n (sqrtPriceX96, , , , , , , ) = IAlgebraPool(algebraPool).globalState();\\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, ) = IAlgebraPool(algebraPool)\\n .getTimepoints(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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceQ96)\\n {\\n // sqrtPriceX96^2 / 2^96 = priceQ96\\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\\n }\\n}\\n\",\"keccak256\":\"0x24a0a3577edb288c7a0718bf3955d868fb6c5b28aa6c347073b07e4b3c8efe73\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b50611620806100206000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c806327e30db11461005c578063506fbf1f1461008557806395240738146100a6578063bd9644a7146100b9578063dd19ebd0146100cc575b600080fd5b61006f61006a366004610c79565b6100ec565b60405161007c9190610cd8565b60405180910390f35b610098610093366004610c79565b610186565b60405190815260200161007c565b61006f6100b4366004610db7565b61033f565b6100986100c7366004610ea9565b610368565b6100df6100da366004610ea9565b61042e565b60405161007c9190610f3e565b6000602081905290815260409020805461010590610fbd565b80601f016020809104026020016040519081016040528092919081815260200182805461013190610fbd565b801561017e5780601f106101535761010080835404028352916020019161017e565b820191906000526020600020905b81548152906001019060200180831161016157829003601f168201915b505050505081565b600081815260208190526040812080548291906101a290610fbd565b80601f01602080910402602001604051908101604052809291908181526020018280546101ce90610fbd565b801561021b5780601f106101f05761010080835404028352916020019161021b565b820191906000526020600020905b8154815290600101906020018083116101fe57829003601f168201915b50505050509050600081511161026a5760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b60006102758261042e565b9050600160601b925060005b81518110156103375760006102ae8383815181106102a1576102a1610ff7565b60200260200101516104a8565b604051631c0e258560e21b8152600481018790526024810182905290915073E00384587DC733D1E201e1EAa5583645d351C01C90637038961490604401602060405180830381865af4158015610308573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061032c919061100d565b945050600101610281565b505050919050565b6060816040516020016103529190610f3e565b6040516020818303038152906040529050919050565b6000806103748361042e565b9050805160011480610387575080516002145b6103ca5760405162461bcd60e51b81526020600482015260146024820152730d2dcecc2d8d2c840e4deeae8ca40d8cadccee8d60631b6044820152606401610261565b825160208085019190912060008181529182905260409091206103ed8582611077565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d4818560405161041f929190611137565b60405180910390a19392505050565b6060818060200190518101906104449190611158565b9050805160011480610457575080516002145b6104a35760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610261565b919050565b6000806104bd836000015184604001516104f0565b90506104c8816106ce565b60208401519092501580156104e9576104e6600160601b80856106e4565b92505b5050919050565b60008163ffffffff1660000361057357826001600160a01b031663e76c01e46040518163ffffffff1660e01b815260040161010060405180830381865afa15801561053f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610563919061125c565b509596506106c895505050505050565b60408051600280825260608201835260009260208301908036833701905050905061059f836001611319565b816000815181106105b2576105b2610ff7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106105e1576105e1610ff7565b63ffffffff90921660209283029190910190910152604051639d3a524160e01b81526000906001600160a01b03861690639d3a52419061062590859060040161133d565b600060405180830381865afa158015610642573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261066a91908101906113fa565b5090506106c38460030b8260008151811061068757610687610ff7565b6020026020010151836001815181106106a2576106a2610ff7565b60200260200101516106b491906114c6565b6106be9190611509565b61085f565b925050505b92915050565b60006106c86001600160a01b03831680600160601b5b600080806000198587098587029250828110838203039150508060000361071d576000841161071257600080fd5b508290049050610858565b80841161072957600080fd5b60008486880980840393811190920391905060008561074a81196001611547565b1695869004959384900493600081900304600101905061076a818461155a565b90931792600061077b87600361155a565b600218905061078a818861155a565b610795906002611571565b61079f908261155a565b90506107ab818861155a565b6107b6906002611571565b6107c0908261155a565b90506107cc818861155a565b6107d7906002611571565b6107e1908261155a565b90506107ed818861155a565b6107f8906002611571565b610802908261155a565b905061080e818861155a565b610819906002611571565b610823908261155a565b905061082f818861155a565b61083a906002611571565b610844908261155a565b9050610850818661155a565b955050505050505b9392505050565b60008060008360020b12610876578260020b610883565b8260020b61088390611584565b9050610892620d89e7196115a0565b62ffffff168111156108ca5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610261565b6000816001166000036108e157600160801b6108f3565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561093257608061092d826ffff97272373d413259a46990580e213a61155a565b901c90505b600482161561095c576080610957826ffff2e50f5f656932ef12357cf3c7fdcc61155a565b901c90505b6008821615610986576080610981826fffe5caca7e10e4e61c3624eaa0941cd061155a565b901c90505b60108216156109b05760806109ab826fffcb9843d60f6159c9db58835c92664461155a565b901c90505b60208216156109da5760806109d5826fff973b41fa98c081472e6896dfb254c061155a565b901c90505b6040821615610a045760806109ff826fff2ea16466c96a3843ec78b326b5286161155a565b901c90505b6080821615610a2e576080610a29826ffe5dee046a99a2a811c461f1969c305361155a565b901c90505b610100821615610a59576080610a54826ffcbe86c7900a88aedcffc83b479aa3a461155a565b901c90505b610200821615610a84576080610a7f826ff987a7253ac413176f2b074cf7815e5461155a565b901c90505b610400821615610aaf576080610aaa826ff3392b0822b70005940c7a398e4b70f361155a565b901c90505b610800821615610ada576080610ad5826fe7159475a2c29b7443b29c7fa6e889d961155a565b901c90505b611000821615610b05576080610b00826fd097f3bdfd2022b8845ad8f792aa582561155a565b901c90505b612000821615610b30576080610b2b826fa9f746462d870fdf8a65dc1f90e061e561155a565b901c90505b614000821615610b5b576080610b56826f70d869a156d2a1b890bb3df62baf32f761155a565b901c90505b618000821615610b86576080610b81826f31be135f97d08fd981231505542fcfa661155a565b901c90505b62010000821615610bb2576080610bad826f09aa508b5b7a84e1c677de54f3e99bc961155a565b901c90505b62020000821615610bdd576080610bd8826e5d6af8dedb81196699c329225ee60461155a565b901c90505b62040000821615610c07576080610c02826d2216e584f5fa1ea926041bedfe9861155a565b901c90505b62080000821615610c2f576080610c2a826b048a170391f7dc42444e8fa261155a565b901c90505b60008460020b1315610c4a57610c47816000196115c2565b90505b610c59640100000000826115d6565b15610c65576001610c68565b60005b6104e69060ff16602083901c611547565b600060208284031215610c8b57600080fd5b5035919050565b6000815180845260005b81811015610cb857602081850181015186830182015201610c9c565b506000602082860101526020601f19601f83011685010191505092915050565b6020815260006108586020830184610c92565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff81118282101715610d2457610d24610ceb565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d5357610d53610ceb565b604052919050565b600067ffffffffffffffff821115610d7557610d75610ceb565b5060051b60200190565b6001600160a01b0381168114610d9457600080fd5b50565b8015158114610d9457600080fd5b63ffffffff81168114610d9457600080fd5b60006020808385031215610dca57600080fd5b823567ffffffffffffffff811115610de157600080fd5b8301601f81018513610df257600080fd5b8035610e05610e0082610d5b565b610d2a565b81815260a09182028301840191848201919088841115610e2457600080fd5b938501935b83851015610e9d5780858a031215610e415760008081fd5b610e49610d01565b8535610e5481610d7f565b815285870135610e6381610d97565b81880152604086810135610e7681610da5565b90820152606086810135908201526080808701359082015283529384019391850191610e29565b50979650505050505050565b60006020808385031215610ebc57600080fd5b823567ffffffffffffffff80821115610ed457600080fd5b818501915085601f830112610ee857600080fd5b813581811115610efa57610efa610ceb565b610f0c601f8201601f19168501610d2a565b91508082528684828501011115610f2257600080fd5b8084840185840137600090820190930192909252509392505050565b602080825282518282018190526000919060409081850190868401855b82811015610fb057815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610f5b565b5091979650505050505050565b600181811c90821680610fd157607f821691505b602082108103610ff157634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561101f57600080fd5b5051919050565b601f821115611072576000816000526020600020601f850160051c8101602086101561104f5750805b601f850160051c820191505b8181101561106e5782815560010161105b565b5050505b505050565b815167ffffffffffffffff81111561109157611091610ceb565b6110a58161109f8454610fbd565b84611026565b602080601f8311600181146110da57600084156110c25750858301515b600019600386901b1c1916600185901b17855561106e565b600085815260208120601f198616915b82811015611109578886015182559484019460019091019084016110ea565b50858210156111275787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b8281526040602082015260006111506040830184610c92565b949350505050565b6000602080838503121561116b57600080fd5b825167ffffffffffffffff81111561118257600080fd5b8301601f8101851361119357600080fd5b80516111a1610e0082610d5b565b81815260a091820283018401918482019190888411156111c057600080fd5b938501935b83851015610e9d5780858a0312156111dd5760008081fd5b6111e5610d01565b85516111f081610d7f565b8152858701516111ff81610d97565b8188015260408681015161121281610da5565b908201526060868101519082015260808087015190820152835293840193918501916111c5565b805161ffff811681146104a357600080fd5b805160ff811681146104a357600080fd5b600080600080600080600080610100898b03121561127957600080fd5b885161128481610d7f565b8098505060208901518060020b811461129c57600080fd5b96506112aa60408a01611239565b95506112b860608a01611239565b94506112c660808a01611239565b93506112d460a08a0161124b565b92506112e260c08a0161124b565b915060e08901516112f281610d97565b809150509295985092959890939650565b634e487b7160e01b600052601160045260246000fd5b63ffffffff81811683821601908082111561133657611336611303565b5092915050565b6020808252825182820181905260009190848201906040850190845b8181101561137b57835163ffffffff1683529284019291840191600101611359565b50909695505050505050565b600082601f83011261139857600080fd5b815160206113a8610e0083610d5b565b8083825260208201915060208460051b8701019350868411156113ca57600080fd5b602086015b848110156113ef5780516113e281610d7f565b83529183019183016113cf565b509695505050505050565b6000806040838503121561140d57600080fd5b825167ffffffffffffffff8082111561142557600080fd5b818501915085601f83011261143957600080fd5b81516020611449610e0083610d5b565b82815260059290921b8401810191818101908984111561146857600080fd5b948201945b838610156114965785518060060b81146114875760008081fd5b8252948201949082019061146d565b918801519196509093505050808211156114af57600080fd5b506114bc85828601611387565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156106c8576106c8611303565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80611520576115206114f3565b667fffffffffffff1982146000198214161561153e5761153e611303565b90059392505050565b808201808211156106c8576106c8611303565b80820281158282048414176106c8576106c8611303565b818103818111156106c8576106c8611303565b6000600160ff1b820161159957611599611303565b5060000390565b60008160020b627fffff1981036115b9576115b9611303565b60000392915050565b6000826115d1576115d16114f3565b500490565b6000826115e5576115e56114f3565b50069056fea26469706673582212207ad00031a9a4aa1ddae4c3cf7fce0dea26b819d3d5d138d63c89c26b912ecdb064736f6c63430008180033", + "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100575760003560e01c806327e30db11461005c578063506fbf1f1461008557806395240738146100a6578063bd9644a7146100b9578063dd19ebd0146100cc575b600080fd5b61006f61006a366004610c79565b6100ec565b60405161007c9190610cd8565b60405180910390f35b610098610093366004610c79565b610186565b60405190815260200161007c565b61006f6100b4366004610db7565b61033f565b6100986100c7366004610ea9565b610368565b6100df6100da366004610ea9565b61042e565b60405161007c9190610f3e565b6000602081905290815260409020805461010590610fbd565b80601f016020809104026020016040519081016040528092919081815260200182805461013190610fbd565b801561017e5780601f106101535761010080835404028352916020019161017e565b820191906000526020600020905b81548152906001019060200180831161016157829003601f168201915b505050505081565b600081815260208190526040812080548291906101a290610fbd565b80601f01602080910402602001604051908101604052809291908181526020018280546101ce90610fbd565b801561021b5780601f106101f05761010080835404028352916020019161021b565b820191906000526020600020905b8154815290600101906020018083116101fe57829003601f168201915b50505050509050600081511161026a5760405162461bcd60e51b815260206004820152600f60248201526e149bdd5d19481b9bdd08199bdd5b99608a1b60448201526064015b60405180910390fd5b60006102758261042e565b9050600160601b925060005b81518110156103375760006102ae8383815181106102a1576102a1610ff7565b60200260200101516104a8565b604051631c0e258560e21b8152600481018790526024810182905290915073__$e1f3d2c8b322d27900ba8e5444ea4bfaba$__90637038961490604401602060405180830381865af4158015610308573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061032c919061100d565b945050600101610281565b505050919050565b6060816040516020016103529190610f3e565b6040516020818303038152906040529050919050565b6000806103748361042e565b9050805160011480610387575080516002145b6103ca5760405162461bcd60e51b81526020600482015260146024820152730d2dcecc2d8d2c840e4deeae8ca40d8cadccee8d60631b6044820152606401610261565b825160208085019190912060008181529182905260409091206103ed8582611077565b507faa804a7933121e854e4cc1c158910d115afcf802449b4ee9084b27801369b5d4818560405161041f929190611137565b60405180910390a19392505050565b6060818060200190518101906104449190611158565b9050805160011480610457575080516002145b6104a35760405162461bcd60e51b815260206004820152601c60248201527f526f757465206d75737420686176652031206f72203220706f6f6c73000000006044820152606401610261565b919050565b6000806104bd836000015184604001516104f0565b90506104c8816106ce565b60208401519092501580156104e9576104e6600160601b80856106e4565b92505b5050919050565b60008163ffffffff1660000361057357826001600160a01b031663e76c01e46040518163ffffffff1660e01b815260040161010060405180830381865afa15801561053f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610563919061125c565b509596506106c895505050505050565b60408051600280825260608201835260009260208301908036833701905050905061059f836001611319565b816000815181106105b2576105b2610ff7565b602002602001019063ffffffff16908163ffffffff16815250506001816001815181106105e1576105e1610ff7565b63ffffffff90921660209283029190910190910152604051639d3a524160e01b81526000906001600160a01b03861690639d3a52419061062590859060040161133d565b600060405180830381865afa158015610642573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261066a91908101906113fa565b5090506106c38460030b8260008151811061068757610687610ff7565b6020026020010151836001815181106106a2576106a2610ff7565b60200260200101516106b491906114c6565b6106be9190611509565b61085f565b925050505b92915050565b60006106c86001600160a01b03831680600160601b5b600080806000198587098587029250828110838203039150508060000361071d576000841161071257600080fd5b508290049050610858565b80841161072957600080fd5b60008486880980840393811190920391905060008561074a81196001611547565b1695869004959384900493600081900304600101905061076a818461155a565b90931792600061077b87600361155a565b600218905061078a818861155a565b610795906002611571565b61079f908261155a565b90506107ab818861155a565b6107b6906002611571565b6107c0908261155a565b90506107cc818861155a565b6107d7906002611571565b6107e1908261155a565b90506107ed818861155a565b6107f8906002611571565b610802908261155a565b905061080e818861155a565b610819906002611571565b610823908261155a565b905061082f818861155a565b61083a906002611571565b610844908261155a565b9050610850818661155a565b955050505050505b9392505050565b60008060008360020b12610876578260020b610883565b8260020b61088390611584565b9050610892620d89e7196115a0565b62ffffff168111156108ca5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610261565b6000816001166000036108e157600160801b6108f3565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561093257608061092d826ffff97272373d413259a46990580e213a61155a565b901c90505b600482161561095c576080610957826ffff2e50f5f656932ef12357cf3c7fdcc61155a565b901c90505b6008821615610986576080610981826fffe5caca7e10e4e61c3624eaa0941cd061155a565b901c90505b60108216156109b05760806109ab826fffcb9843d60f6159c9db58835c92664461155a565b901c90505b60208216156109da5760806109d5826fff973b41fa98c081472e6896dfb254c061155a565b901c90505b6040821615610a045760806109ff826fff2ea16466c96a3843ec78b326b5286161155a565b901c90505b6080821615610a2e576080610a29826ffe5dee046a99a2a811c461f1969c305361155a565b901c90505b610100821615610a59576080610a54826ffcbe86c7900a88aedcffc83b479aa3a461155a565b901c90505b610200821615610a84576080610a7f826ff987a7253ac413176f2b074cf7815e5461155a565b901c90505b610400821615610aaf576080610aaa826ff3392b0822b70005940c7a398e4b70f361155a565b901c90505b610800821615610ada576080610ad5826fe7159475a2c29b7443b29c7fa6e889d961155a565b901c90505b611000821615610b05576080610b00826fd097f3bdfd2022b8845ad8f792aa582561155a565b901c90505b612000821615610b30576080610b2b826fa9f746462d870fdf8a65dc1f90e061e561155a565b901c90505b614000821615610b5b576080610b56826f70d869a156d2a1b890bb3df62baf32f761155a565b901c90505b618000821615610b86576080610b81826f31be135f97d08fd981231505542fcfa661155a565b901c90505b62010000821615610bb2576080610bad826f09aa508b5b7a84e1c677de54f3e99bc961155a565b901c90505b62020000821615610bdd576080610bd8826e5d6af8dedb81196699c329225ee60461155a565b901c90505b62040000821615610c07576080610c02826d2216e584f5fa1ea926041bedfe9861155a565b901c90505b62080000821615610c2f576080610c2a826b048a170391f7dc42444e8fa261155a565b901c90505b60008460020b1315610c4a57610c47816000196115c2565b90505b610c59640100000000826115d6565b15610c65576001610c68565b60005b6104e69060ff16602083901c611547565b600060208284031215610c8b57600080fd5b5035919050565b6000815180845260005b81811015610cb857602081850181015186830182015201610c9c565b506000602082860101526020601f19601f83011685010191505092915050565b6020815260006108586020830184610c92565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff81118282101715610d2457610d24610ceb565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d5357610d53610ceb565b604052919050565b600067ffffffffffffffff821115610d7557610d75610ceb565b5060051b60200190565b6001600160a01b0381168114610d9457600080fd5b50565b8015158114610d9457600080fd5b63ffffffff81168114610d9457600080fd5b60006020808385031215610dca57600080fd5b823567ffffffffffffffff811115610de157600080fd5b8301601f81018513610df257600080fd5b8035610e05610e0082610d5b565b610d2a565b81815260a09182028301840191848201919088841115610e2457600080fd5b938501935b83851015610e9d5780858a031215610e415760008081fd5b610e49610d01565b8535610e5481610d7f565b815285870135610e6381610d97565b81880152604086810135610e7681610da5565b90820152606086810135908201526080808701359082015283529384019391850191610e29565b50979650505050505050565b60006020808385031215610ebc57600080fd5b823567ffffffffffffffff80821115610ed457600080fd5b818501915085601f830112610ee857600080fd5b813581811115610efa57610efa610ceb565b610f0c601f8201601f19168501610d2a565b91508082528684828501011115610f2257600080fd5b8084840185840137600090820190930192909252509392505050565b602080825282518282018190526000919060409081850190868401855b82811015610fb057815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101610f5b565b5091979650505050505050565b600181811c90821680610fd157607f821691505b602082108103610ff157634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561101f57600080fd5b5051919050565b601f821115611072576000816000526020600020601f850160051c8101602086101561104f5750805b601f850160051c820191505b8181101561106e5782815560010161105b565b5050505b505050565b815167ffffffffffffffff81111561109157611091610ceb565b6110a58161109f8454610fbd565b84611026565b602080601f8311600181146110da57600084156110c25750858301515b600019600386901b1c1916600185901b17855561106e565b600085815260208120601f198616915b82811015611109578886015182559484019460019091019084016110ea565b50858210156111275787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b8281526040602082015260006111506040830184610c92565b949350505050565b6000602080838503121561116b57600080fd5b825167ffffffffffffffff81111561118257600080fd5b8301601f8101851361119357600080fd5b80516111a1610e0082610d5b565b81815260a091820283018401918482019190888411156111c057600080fd5b938501935b83851015610e9d5780858a0312156111dd5760008081fd5b6111e5610d01565b85516111f081610d7f565b8152858701516111ff81610d97565b8188015260408681015161121281610da5565b908201526060868101519082015260808087015190820152835293840193918501916111c5565b805161ffff811681146104a357600080fd5b805160ff811681146104a357600080fd5b600080600080600080600080610100898b03121561127957600080fd5b885161128481610d7f565b8098505060208901518060020b811461129c57600080fd5b96506112aa60408a01611239565b95506112b860608a01611239565b94506112c660808a01611239565b93506112d460a08a0161124b565b92506112e260c08a0161124b565b915060e08901516112f281610d97565b809150509295985092959890939650565b634e487b7160e01b600052601160045260246000fd5b63ffffffff81811683821601908082111561133657611336611303565b5092915050565b6020808252825182820181905260009190848201906040850190845b8181101561137b57835163ffffffff1683529284019291840191600101611359565b50909695505050505050565b600082601f83011261139857600080fd5b815160206113a8610e0083610d5b565b8083825260208201915060208460051b8701019350868411156113ca57600080fd5b602086015b848110156113ef5780516113e281610d7f565b83529183019183016113cf565b509695505050505050565b6000806040838503121561140d57600080fd5b825167ffffffffffffffff8082111561142557600080fd5b818501915085601f83011261143957600080fd5b81516020611449610e0083610d5b565b82815260059290921b8401810191818101908984111561146857600080fd5b948201945b838610156114965785518060060b81146114875760008081fd5b8252948201949082019061146d565b918801519196509093505050808211156114af57600080fd5b506114bc85828601611387565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156106c8576106c8611303565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80611520576115206114f3565b667fffffffffffff1982146000198214161561153e5761153e611303565b90059392505050565b808201808211156106c8576106c8611303565b80820281158282048414176106c8576106c8611303565b818103818111156106c8576106c8611303565b6000600160ff1b820161159957611599611303565b5060000390565b60008160020b627fffff1981036115b9576115b9611303565b60000392915050565b6000826115d1576115d16114f3565b500490565b6000826115e5576115e56114f3565b50069056fea26469706673582212207ad00031a9a4aa1ddae4c3cf7fce0dea26b819d3d5d138d63c89c26b912ecdb064736f6c63430008180033", + "libraries": { + "FixedPointQ96": "0xE00384587DC733D1E201e1EAa5583645d351C01C" + }, + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 77718, + "contract": "contracts/price_adapters/PriceAdapterAlgebra.sol:PriceAdapterAlgebra", + "label": "priceRoutes", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_bytes32,t_bytes_storage)" + } + ], + "types": { + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_bytes_storage)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => bytes)", + "numberOfBytes": "32", + "value": "t_bytes_storage" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/apechain/solcInputs/3b875778126b5c8a21485ac9e3e615af.json b/packages/contracts/deployments/apechain/solcInputs/3b875778126b5c8a21485ac9e3e615af.json new file mode 100644 index 000000000..95ccabe8a --- /dev/null +++ b/packages/contracts/deployments/apechain/solcInputs/3b875778126b5c8a21485ac9e3e615af.json @@ -0,0 +1,1002 @@ +{ + "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/metatx/MinimalForwarderUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/cryptography/EIP712Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.\n *\n * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This\n * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully\n * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects\n * such as the GSN which do have the goal of building a system like that.\n */\ncontract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {\n using ECDSAUpgradeable for bytes32;\n\n struct ForwardRequest {\n address from;\n address to;\n uint256 value;\n uint256 gas;\n uint256 nonce;\n bytes data;\n }\n\n bytes32 private constant _TYPEHASH =\n keccak256(\"ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)\");\n\n mapping(address => uint256) private _nonces;\n\n function __MinimalForwarder_init() internal onlyInitializing {\n __EIP712_init_unchained(\"MinimalForwarder\", \"0.0.1\");\n }\n\n function __MinimalForwarder_init_unchained() internal onlyInitializing {}\n\n function getNonce(address from) public view returns (uint256) {\n return _nonces[from];\n }\n\n function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {\n address signer = _hashTypedDataV4(\n keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))\n ).recover(signature);\n return _nonces[req.from] == req.nonce && signer == req.from;\n }\n\n function execute(ForwardRequest calldata req, bytes calldata signature)\n public\n payable\n returns (bool, bytes memory)\n {\n require(verify(req, signature), \"MinimalForwarder: signature does not match request\");\n _nonces[req.from] = req.nonce + 1;\n\n (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(\n abi.encodePacked(req.data, req.from)\n );\n\n // Validate that the relayer has sent enough gas for the call.\n // See https://ronan.eth.limo/blog/ethereum-gas-dangers/\n if (gasleft() <= req.gas / 63) {\n // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since\n // neither revert or assert consume all gas since Solidity 0.8.0\n // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require\n /// @solidity memory-safe-assembly\n assembly {\n invalid()\n }\n }\n\n return (success, returndata);\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/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/ERC1155/IERC1155Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\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 function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\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 /**\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[45] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-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/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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, /* firstTokenId */\n uint256 batchSize\n ) internal virtual {\n if (batchSize > 1) {\n if (from != address(0)) {\n _balances[from] -= batchSize;\n }\n if (to != address(0)) {\n _balances[to] += batchSize;\n }\n }\n }\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-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 firstTokenId,\n uint256 batchSize\n ) internal virtual {}\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[44] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/token/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/ECDSAUpgradeable.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 \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // 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\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.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 \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin/contracts-upgradeable/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/StringsUpgradeable.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/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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, MathUpgradeable.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-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/AccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" + }, + "@openzeppelin/contracts/access/AccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerable.sol\";\nimport \"./AccessControl.sol\";\nimport \"../utils/structs/EnumerableSet.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControlEnumerable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\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/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/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/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\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) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * 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/security/Pausable.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/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev 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" + }, + "@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/ERC20Burnable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../../../security/Pausable.sol\";\n\n/**\n * @dev ERC20 token with pausable token transfers, minting and burning.\n *\n * Useful for scenarios such as preventing trades until the end of an evaluation\n * period, or having an emergency switch for freezing all token transfers in the\n * event of a large bug.\n */\nabstract contract ERC20Pausable is ERC20, Pausable {\n /**\n * @dev See {ERC20-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n require(!paused(), \"ERC20Pausable: token transfer while paused\");\n }\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/presets/ERC20PresetMinterPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20.sol\";\nimport \"../extensions/ERC20Burnable.sol\";\nimport \"../extensions/ERC20Pausable.sol\";\nimport \"../../../access/AccessControlEnumerable.sol\";\nimport \"../../../utils/Context.sol\";\n\n/**\n * @dev {ERC20} token, including:\n *\n * - ability for holders to burn (destroy) their tokens\n * - a minter role that allows for token minting (creation)\n * - a pauser role that allows to stop all token transfers\n *\n * This contract uses {AccessControl} to lock permissioned functions using the\n * different roles - head to its documentation for details.\n *\n * The account that deploys the contract will be granted the minter and pauser\n * roles, as well as the default admin role, which will let it grant both minter\n * and pauser roles to other accounts.\n *\n * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._\n */\ncontract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable {\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n /**\n * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the\n * account that deploys the contract.\n *\n * See {ERC20-constructor}.\n */\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {\n _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n\n _setupRole(MINTER_ROLE, _msgSender());\n _setupRole(PAUSER_ROLE, _msgSender());\n }\n\n /**\n * @dev Creates `amount` new tokens for `to`.\n *\n * See {ERC20-_mint}.\n *\n * Requirements:\n *\n * - the caller must have the `MINTER_ROLE`.\n */\n function mint(address to, uint256 amount) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have minter role to mint\");\n _mint(to, amount);\n }\n\n /**\n * @dev Pauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function pause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to pause\");\n _pause();\n }\n\n /**\n * @dev Unpauses all token transfers.\n *\n * See {ERC20Pausable} and {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the `PAUSER_ROLE`.\n */\n function unpause() public virtual {\n require(hasRole(PAUSER_ROLE, _msgSender()), \"ERC20PresetMinterPauser: must have pauser role to unpause\");\n _unpause();\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20, ERC20Pausable) {\n super._beforeTokenTransfer(from, to, amount);\n }\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/introspection/ERC165.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@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/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\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" + }, + "@uniswap/v4-core/src/interfaces/external/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns an account's balance in the token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/external/IERC6909Claims.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n FUNCTIONS\n //////////////////////////////////////////////////////////////*/\n\n /// @notice Owner balance of an id.\n /// @param owner The address of the owner.\n /// @param id The id of the token.\n /// @return amount The balance of the token.\n function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n /// @notice Spender allowance of an id.\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @return amount The allowance of the token.\n function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n /// @notice Checks if a spender is approved by an owner as an operator\n /// @param owner The address of the owner.\n /// @param spender The address of the spender.\n /// @return approved The approval status.\n function isOperator(address owner, address spender) external view returns (bool approved);\n\n /// @notice Transfers an amount of an id from the caller to a receiver.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Transfers an amount of an id from a sender to a receiver.\n /// @param sender The address of the sender.\n /// @param receiver The address of the receiver.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always, unless the function reverts\n function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Approves an amount of an id to a spender.\n /// @param spender The address of the spender.\n /// @param id The id of the token.\n /// @param amount The amount of the token.\n /// @return bool True, always\n function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n /// @notice Sets or removes an operator for the caller.\n /// @param operator The address of the operator.\n /// @param approved The approval status.\n /// @return bool True, always\n function setOperator(address operator, bool approved) external returns (bool);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExtsload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n /// @notice Called by external contracts to access granular pool state\n /// @param slot Key of slot to sload\n /// @return value The value of the slot as bytes32\n function extsload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access granular pool state\n /// @param startSlot Key of slot to start sloading from\n /// @param nSlots Number of slots to load into return value\n /// @return values List of loaded values.\n function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n /// @notice Called by external contracts to access sparse pool state\n /// @param slots List of slots to SLOAD from.\n /// @return values List of loaded values.\n function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IExttload.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n /// @notice Called by external contracts to access transient storage of the contract\n /// @param slot Key of slot to tload\n /// @return value The value of the slot as bytes32\n function exttload(bytes32 slot) external view returns (bytes32 value);\n\n /// @notice Called by external contracts to access sparse transient pool state\n /// @param slots List of slots to tload\n /// @return values List of loaded values\n function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IHooks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n /// @notice The hook called before the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @return bytes4 The function selector for the hook\n function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n /// @notice The hook called after the state of a pool is initialized\n /// @param sender The initial msg.sender for the initialize call\n /// @param key The key for the pool being initialized\n /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n /// @param tick The current tick after the state of a pool is initialized\n /// @return bytes4 The function selector for the hook\n function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n external\n returns (bytes4);\n\n /// @notice The hook called before liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is added\n /// @param sender The initial msg.sender for the add liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for adding liquidity\n /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterAddLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after liquidity is removed\n /// @param sender The initial msg.sender for the remove liquidity call\n /// @param key The key for the pool\n /// @param params The parameters for removing liquidity\n /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterRemoveLiquidity(\n address sender,\n PoolKey calldata key,\n ModifyLiquidityParams calldata params,\n BalanceDelta delta,\n BalanceDelta feesAccrued,\n bytes calldata hookData\n ) external returns (bytes4, BalanceDelta);\n\n /// @notice The hook called before a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)\n function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)\n external\n returns (bytes4, BeforeSwapDelta, uint24);\n\n /// @notice The hook called after a swap\n /// @param sender The initial msg.sender for the swap call\n /// @param key The key for the pool\n /// @param params The parameters for the swap\n /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n function afterSwap(\n address sender,\n PoolKey calldata key,\n SwapParams calldata params,\n BalanceDelta delta,\n bytes calldata hookData\n ) external returns (bytes4, int128);\n\n /// @notice The hook called before donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function beforeDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n\n /// @notice The hook called after donate\n /// @param sender The initial msg.sender for the donate call\n /// @param key The key for the pool\n /// @param amount0 The amount of token0 being donated\n /// @param amount1 The amount of token1 being donated\n /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n /// @return bytes4 The function selector for the hook\n function afterDonate(\n address sender,\n PoolKey calldata key,\n uint256 amount0,\n uint256 amount1,\n bytes calldata hookData\n ) external returns (bytes4);\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IPoolManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\nimport {ModifyLiquidityParams, SwapParams} from \"../types/PoolOperation.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n /// @notice Thrown when a currency is not netted out after the contract is unlocked\n error CurrencyNotSettled();\n\n /// @notice Thrown when trying to interact with a non-initialized pool\n error PoolNotInitialized();\n\n /// @notice Thrown when unlock is called, but the contract is already unlocked\n error AlreadyUnlocked();\n\n /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n error ManagerLocked();\n\n /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n error TickSpacingTooLarge(int24 tickSpacing);\n\n /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n error TickSpacingTooSmall(int24 tickSpacing);\n\n /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n /// or on a pool that does not have a dynamic swap fee.\n error UnauthorizedDynamicLPFeeUpdate();\n\n /// @notice Thrown when trying to swap amount of 0\n error SwapAmountCannotBeZero();\n\n ///@notice Thrown when native currency is passed to a non native settlement\n error NonzeroNativeValue();\n\n /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n error MustClearExactPositiveDelta();\n\n /// @notice Emitted when a new pool is initialized\n /// @param id The abi encoded hash of the pool key struct for the new pool\n /// @param currency0 The first currency of the pool by address sort order\n /// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none\n /// @param sqrtPriceX96 The price of the pool on initialization\n /// @param tick The initial tick of the pool corresponding to the initialized price\n event Initialize(\n PoolId indexed id,\n Currency indexed currency0,\n Currency indexed currency1,\n uint24 fee,\n int24 tickSpacing,\n IHooks hooks,\n uint160 sqrtPriceX96,\n int24 tick\n );\n\n /// @notice Emitted when a liquidity position is modified\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that modified the pool\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param liquidityDelta The amount of liquidity that was added or removed\n /// @param salt The extra data to make positions unique\n event ModifyLiquidity(\n PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n );\n\n /// @notice Emitted for swaps between currency0 and currency1\n /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param amount0 The delta of the currency0 balance of the pool\n /// @param amount1 The delta of the currency1 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 the price of the pool after the swap\n /// @param fee The swap fee in hundredths of a bip\n event Swap(\n PoolId indexed id,\n address indexed sender,\n int128 amount0,\n int128 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick,\n uint24 fee\n );\n\n /// @notice Emitted for donations\n /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n /// @param sender The address that initiated the donate call\n /// @param amount0 The amount donated in currency0\n /// @param amount1 The amount donated in currency1\n event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n function unlock(bytes calldata data) external returns (bytes memory);\n\n /// @notice Initialize the state for a given pool ID\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The pool key for the pool to initialize\n /// @param sqrtPriceX96 The initial square root price\n /// @return tick The initial tick of the pool\n function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n /// @notice Modify the liquidity for the given pool\n /// @dev Poke by calling with a zero liquidityDelta\n /// @param key The pool to modify liquidity in\n /// @param params The parameters for modifying the liquidity\n /// @param hookData The data to pass through to the add/removeLiquidity hooks\n /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n /// @notice Swap against the given pool\n /// @param key The pool to swap in\n /// @param params The parameters for swapping\n /// @param hookData The data to pass through to the swap hooks\n /// @return swapDelta The balance delta of the address swapping\n /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n external\n returns (BalanceDelta swapDelta);\n\n /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n /// Donors should keep this in mind when designing donation mechanisms.\n /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to\n /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n /// Read the comments in `Pool.swap()` for more information about this.\n /// @param key The key of the pool to donate to\n /// @param amount0 The amount of currency0 to donate\n /// @param amount1 The amount of currency1 to donate\n /// @param hookData The data to pass through to the donate hooks\n /// @return BalanceDelta The delta of the caller after the donate\n function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n external\n returns (BalanceDelta);\n\n /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n /// for native tokens because the amount to settle is determined by the sent value.\n /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n /// native funds, this function can be called with the native currency to then be able to settle the native currency\n function sync(Currency currency) external;\n\n /// @notice Called by the user to net out some value owed to the user\n /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n /// @dev Can also be used as a mechanism for free flash loans\n /// @param currency The currency to withdraw from the pool manager\n /// @param to The address to withdraw to\n /// @param amount The amount of currency to withdraw\n function take(Currency currency, address to, uint256 amount) external;\n\n /// @notice Called by the user to pay what is owed\n /// @return paid The amount of currency settled\n function settle() external payable returns (uint256 paid);\n\n /// @notice Called by the user to pay on behalf of another address\n /// @param recipient The address to credit for the payment\n /// @return paid The amount of currency settled\n function settleFor(address recipient) external payable returns (uint256 paid);\n\n /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n /// @dev This could be used to clear a balance that is considered dust.\n /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n function clear(Currency currency, uint256 amount) external;\n\n /// @notice Called by the user to move value into ERC6909 balance\n /// @param to The address to mint the tokens to\n /// @param id The currency address to mint to ERC6909s, as a uint256\n /// @param amount The amount of currency to mint\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function mint(address to, uint256 id, uint256 amount) external;\n\n /// @notice Called by the user to move value from ERC6909 balance\n /// @param from The address to burn the tokens from\n /// @param id The currency address to burn from ERC6909s, as a uint256\n /// @param amount The amount of currency to burn\n /// @dev The id is converted to a uint160 to correspond to a currency address\n /// If the upper 12 bytes are not 0, they will be 0-ed out\n function burn(address from, uint256 id, uint256 amount) external;\n\n /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n /// @param key The key of the pool to update dynamic LP fees for\n /// @param newDynamicLPFee The new dynamic pool LP fee\n function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n" + }, + "@uniswap/v4-core/src/interfaces/IProtocolFees.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n /// @notice Thrown when protocol fee is set too high\n error ProtocolFeeTooLarge(uint24 fee);\n\n /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n error InvalidCaller();\n\n /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n error ProtocolFeeCurrencySynced();\n\n /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n /// @notice Emitted when the protocol fee is updated for a pool.\n event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n /// @notice Given a currency address, returns the protocol fees accrued in that currency\n /// @param currency The currency to check\n /// @return amount The amount of protocol fees accrued in the currency\n function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n /// @notice Sets the protocol fee for the given pool\n /// @param key The key of the pool to set a protocol fee for\n /// @param newProtocolFee The fee to set\n function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n /// @notice Sets the protocol fee controller\n /// @param controller The new protocol fee controller\n function setProtocolFeeController(address controller) external;\n\n /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n /// @dev This will revert if the contract is unlocked\n /// @param recipient The address to receive the protocol fees\n /// @param currency The currency to withdraw\n /// @param amount The amount of currency to withdraw\n /// @return amountCollected The amount of currency successfully withdrawn\n function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n external\n returns (uint256 amountCollected);\n\n /// @notice Returns the current protocol fee controller address\n /// @return address The current protocol fee controller address\n function protocolFeeController() external view returns (address);\n}\n" + }, + "@uniswap/v4-core/src/libraries/CustomRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n /// @dev ERC-7751 error for wrapping bubbled up reverts\n error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n /// @dev Reverts with the selector of a custom error in the scratch space\n function revertWith(bytes4 selector) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n revert(0, 0x04)\n }\n }\n\n /// @dev Reverts with a custom error with an address argument in the scratch space\n function revertWith(bytes4 selector, address addr) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with an int24 argument in the scratch space\n function revertWith(bytes4 selector, int24 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, signextend(2, value))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n function revertWith(bytes4 selector, uint160 value) internal pure {\n assembly (\"memory-safe\") {\n mstore(0, selector)\n mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(0, 0x24)\n }\n }\n\n /// @dev Reverts with a custom error with two int24 arguments\n function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), signextend(2, value1))\n mstore(add(fmp, 0x24), signextend(2, value2))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two uint160 arguments\n function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @dev Reverts with a custom error with two address arguments\n function revertWith(bytes4 selector, address value1, address value2) internal pure {\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(fmp, selector)\n mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n revert(fmp, 0x44)\n }\n }\n\n /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n /// @dev this method can be vulnerable to revert data bombs\n function bubbleUpAndRevertWith(\n address revertingContract,\n bytes4 revertingFunctionSelector,\n bytes4 additionalContext\n ) internal pure {\n bytes4 wrappedErrorSelector = WrappedError.selector;\n assembly (\"memory-safe\") {\n // Ensure the size of the revert data is a multiple of 32 bytes\n let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n let fmp := mload(0x40)\n\n // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n mstore(fmp, wrappedErrorSelector)\n mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n mstore(\n add(fmp, 0x24),\n and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n // offset revert reason\n mstore(add(fmp, 0x44), 0x80)\n // offset additional context\n mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n // size revert reason\n mstore(add(fmp, 0x84), returndatasize())\n // revert reason\n returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n // size additional context\n mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n // additional context\n mstore(\n add(fmp, add(0xc4, encodedDataSize)),\n and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n )\n revert(fmp, add(0xe4, encodedDataSize))\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/FixedPoint128.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n" + }, + "@uniswap/v4-core/src/libraries/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) internal pure returns (uint256 result) {\n unchecked {\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 = a * b; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly (\"memory-safe\") {\n let mm := mulmod(a, b, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n assembly (\"memory-safe\") {\n result := div(prod0, denominator)\n }\n return result;\n }\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 (\"memory-safe\") {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly (\"memory-safe\") {\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 = (0 - denominator) & denominator;\n // Divide denominator by power of two\n assembly (\"memory-safe\") {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly (\"memory-safe\") {\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 (\"memory-safe\") {\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 preconditions 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\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) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) != 0) {\n require(++result > 0);\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n assembly (\"memory-safe\") {\n z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n if shr(128, z) {\n // revert SafeCastOverflow()\n mstore(0, 0x93dafdf1)\n revert(0x1c, 0x04)\n }\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/Position.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n using CustomRevert for bytes4;\n\n /// @notice Cannot update a position with no liquidity\n error CannotUpdateEmptyPosition();\n\n // info stored for each user's position\n struct State {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n }\n\n /// @notice Returns the State struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range\n /// @return position The position info struct of the given owners' position\n function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n view\n returns (State storage position)\n {\n bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n position = self[positionKey];\n }\n\n /// @notice A helper function to calculate the position key\n /// @param owner The address of the position owner\n /// @param tickLower the lower tick boundary of the position\n /// @param tickUpper the upper tick boundary of the position\n /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n internal\n pure\n returns (bytes32 positionKey)\n {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n assembly (\"memory-safe\") {\n let fmp := mload(0x40)\n mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n mstore(fmp, owner) // [0x0c, 0x20)\n positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n // now clean the memory we used\n mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n mstore(fmp, 0) // fmp held owner\n }\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n /// @return feesOwed0 The amount of currency0 owed to the position owner\n /// @return feesOwed1 The amount of currency1 owed to the position owner\n function update(\n State storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n uint128 liquidity = self.liquidity;\n\n if (liquidityDelta == 0) {\n // disallow pokes for 0 liquidity positions\n if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n } else {\n self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n unchecked {\n feesOwed0 =\n FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n feesOwed1 =\n FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n }\n\n // update the position\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n using CustomRevert for bytes4;\n\n error SafeCastOverflow();\n\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint160\n function toUint160(uint256 x) internal pure returns (uint160 y) {\n y = uint160(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a uint128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return y The downcasted integer, now type uint128\n function toUint128(uint256 x) internal pure returns (uint128 y) {\n y = uint128(x);\n if (x != y) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n /// @param x The int128 to be casted\n /// @return y The casted integer, now type uint128\n function toUint128(int128 x) internal pure returns (uint128 y) {\n if (x < 0) SafeCastOverflow.selector.revertWith();\n y = uint128(x);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param x The int256 to be downcasted\n /// @return y The downcasted integer, now type int128\n function toInt128(int256 x) internal pure returns (int128 y) {\n y = int128(x);\n if (y != x) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param x The uint256 to be casted\n /// @return y The casted integer, now type int256\n function toInt256(uint256 x) internal pure returns (int256 y) {\n y = int256(x);\n if (y < 0) SafeCastOverflow.selector.revertWith();\n }\n\n /// @notice Cast a uint256 to a int128, revert on overflow\n /// @param x The uint256 to be downcasted\n /// @return The downcasted integer, now type int128\n function toInt128(uint256 x) internal pure returns (int128) {\n if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n return int128(int256(x));\n }\n}\n" + }, + "@uniswap/v4-core/src/libraries/StateLibrary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n /// @notice index of pools mapping in the PoolManager\n bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n /// @notice index of feeGrowthGlobal0X128 in Pool.State\n uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n /// @notice index of liquidity in Pool.State\n uint256 public constant LIQUIDITY_OFFSET = 3;\n\n /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n uint256 public constant TICKS_OFFSET = 4;\n\n /// @notice index of tickBitmap mapping in Pool.State\n uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n uint256 public constant POSITIONS_OFFSET = 6;\n\n /**\n * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n * @dev Corresponds to pools[poolId].slot0\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n * @return tick The current tick of the pool.\n * @return protocolFee The protocol fee of the pool.\n * @return lpFee The swap fee of the pool.\n */\n function getSlot0(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n bytes32 data = manager.extsload(stateSlot);\n\n // 24 bits |24bits|24bits |24 bits|160 bits\n // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n // ---------- | fee |protocolfee | tick | sqrtPriceX96\n assembly (\"memory-safe\") {\n // bottom 160 bits of data\n sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n // next 24 bits of data\n tick := signextend(2, shr(160, data))\n // next 24 bits of data\n protocolFee := and(shr(184, data), 0xFFFFFF)\n // last 24 bits of data\n lpFee := and(shr(208, data), 0xFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the tick information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve information for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n )\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // read all 3 words of the TickInfo struct\n bytes32[] memory data = manager.extsload(slot, 3);\n assembly (\"memory-safe\") {\n let firstWord := mload(add(data, 32))\n liquidityNet := sar(128, firstWord)\n liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n feeGrowthOutside0X128 := mload(add(data, 64))\n feeGrowthOutside1X128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity information of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve liquidity for.\n * @return liquidityGross The total position liquidity that references this tick\n * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n */\n function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint128 liquidityGross, int128 liquidityNet)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n bytes32 value = manager.extsload(slot);\n assembly (\"memory-safe\") {\n liquidityNet := sar(128, value)\n liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n }\n }\n\n /**\n * @notice Retrieves the fee growth outside a tick range of a pool\n * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve fee growth for.\n * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n */\n function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n internal\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n {\n bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n // offset by 1 word, since the first word is liquidityGross + liquidityNet\n bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n assembly (\"memory-safe\") {\n feeGrowthOutside0X128 := mload(add(data, 32))\n feeGrowthOutside1X128 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves the global fee growth of a pool.\n * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return feeGrowthGlobal0 The global fee growth for token0.\n * @return feeGrowthGlobal1 The global fee growth for token1.\n * @dev Note that feeGrowthGlobal can be artificially inflated\n * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n */\n function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n internal\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State, `uint256 feeGrowthGlobal0X128`\n bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n // read the 2 words of feeGrowthGlobal\n bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n assembly (\"memory-safe\") {\n feeGrowthGlobal0 := mload(add(data, 32))\n feeGrowthGlobal1 := mload(add(data, 64))\n }\n }\n\n /**\n * @notice Retrieves total the liquidity of a pool.\n * @dev Corresponds to pools[poolId].liquidity\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @return liquidity The liquidity of the pool.\n */\n function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `uint128 liquidity`\n bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Retrieves the tick bitmap of a pool at a specific tick.\n * @dev Corresponds to pools[poolId].tickBitmap[tick]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tick The tick to retrieve the bitmap for.\n * @return tickBitmap The bitmap of the tick.\n */\n function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n internal\n view\n returns (uint256 tickBitmap)\n {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n tickBitmap = uint256(manager.extsload(slot));\n }\n\n /**\n * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param poolId The ID of the pool.\n * @param owner The owner of the liquidity position.\n * @param tickLower The lower tick of the liquidity range.\n * @param tickUpper The upper tick of the liquidity range.\n * @param salt The bytes32 randomness to further distinguish position state.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(\n IPoolManager manager,\n PoolId poolId,\n address owner,\n int24 tickLower,\n int24 tickUpper,\n bytes32 salt\n ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n }\n\n /**\n * @notice Retrieves the position information of a pool at a specific position ID.\n * @dev Corresponds to pools[poolId].positions[positionId]\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n */\n function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n // read all 3 words of the Position.State struct\n bytes32[] memory data = manager.extsload(slot, 3);\n\n assembly (\"memory-safe\") {\n liquidity := mload(add(data, 32))\n feeGrowthInside0LastX128 := mload(add(data, 64))\n feeGrowthInside1LastX128 := mload(add(data, 96))\n }\n }\n\n /**\n * @notice Retrieves the liquidity of a position.\n * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param positionId The ID of the position.\n * @return liquidity The liquidity of the position.\n */\n function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n internal\n view\n returns (uint128 liquidity)\n {\n bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n liquidity = uint128(uint256(manager.extsload(slot)));\n }\n\n /**\n * @notice Calculate the fee growth inside a tick range of a pool\n * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n * @param manager The pool manager contract.\n * @param poolId The ID of the pool.\n * @param tickLower The lower tick of the range.\n * @param tickUpper The upper tick of the range.\n * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n */\n function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n internal\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n {\n (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickLower);\n (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n getTickFeeGrowthOutside(manager, poolId, tickUpper);\n (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n unchecked {\n if (tickCurrent < tickLower) {\n feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n } else if (tickCurrent >= tickUpper) {\n feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n } else {\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n }\n }\n }\n\n function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n }\n\n function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(int24 => TickInfo) ticks`\n bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n // slot key of the tick key: `pools[poolId].ticks[tick]\n return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n }\n\n function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n // slot key of Pool.State value: `pools[poolId]`\n bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n // Pool.State: `mapping(bytes32 => Position.State) positions;`\n bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n // slot of the mapping key: `pools[poolId].positions[positionId]\n return keccak256(abi.encodePacked(positionId, positionMapping));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BalanceDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n assembly (\"memory-safe\") {\n balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := add(a0, b0)\n res1 := add(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n int256 res0;\n int256 res1;\n assembly (\"memory-safe\") {\n let a0 := sar(128, a)\n let a1 := signextend(15, a)\n let b0 := sar(128, b)\n let b1 := signextend(15, b)\n res0 := sub(a0, b0)\n res1 := sub(a1, b1)\n }\n return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n /// @notice A BalanceDelta of 0\n BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n assembly (\"memory-safe\") {\n _amount0 := sar(128, balanceDelta)\n }\n }\n\n function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n assembly (\"memory-safe\") {\n _amount1 := signextend(15, balanceDelta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/BeforeSwapDelta.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n pure\n returns (BeforeSwapDelta beforeSwapDelta)\n{\n assembly (\"memory-safe\") {\n beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n /// @notice A BeforeSwapDelta of 0\n BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap\n function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n assembly (\"memory-safe\") {\n deltaSpecified := sar(128, delta)\n }\n }\n\n /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n /// returned by beforeSwap and afterSwap\n function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n assembly (\"memory-safe\") {\n deltaUnspecified := signextend(15, delta)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/Currency.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n error NativeTransferFailed();\n\n /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n error ERC20TransferFailed();\n\n /// @notice A constant to represent the native currency\n Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n function transfer(Currency currency, address to, uint256 amount) internal {\n // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n // modified custom error selectors\n\n bool success;\n if (currency.isAddressZero()) {\n assembly (\"memory-safe\") {\n // Transfer the ETH and revert if it fails.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n // revert with NativeTransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n }\n } else {\n assembly (\"memory-safe\") {\n // Get a pointer to some free memory.\n let fmp := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n success :=\n and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), currency, 0, fmp, 68, 0, 32)\n )\n\n // Now clean the memory we used\n mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n }\n // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n if (!success) {\n CustomRevert.bubbleUpAndRevertWith(\n Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n );\n }\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return address(this).balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n }\n }\n\n function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n if (currency.isAddressZero()) {\n return owner.balance;\n } else {\n return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n }\n }\n\n function isAddressZero(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n }\n\n function toId(Currency currency) internal pure returns (uint256) {\n return uint160(Currency.unwrap(currency));\n }\n\n // If the upper 12 bytes are non-zero, they will be zero-ed out\n // Therefore, fromId() and toId() are not inverses of each other\n function fromId(uint256 id) internal pure returns (Currency) {\n return Currency.wrap(address(uint160(id)));\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolId.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n assembly (\"memory-safe\") {\n // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n poolId := keccak256(poolKey, 0xa0)\n }\n }\n}\n" + }, + "@uniswap/v4-core/src/types/PoolKey.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n /// @notice The lower currency of the pool, sorted numerically\n Currency currency0;\n /// @notice The higher currency of the pool, sorted numerically\n Currency currency1;\n /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000\n uint24 fee;\n /// @notice Ticks that involve positions must be a multiple of tick spacing\n int24 tickSpacing;\n /// @notice The hooks of the pool\n IHooks hooks;\n}\n" + }, + "@uniswap/v4-core/src/types/PoolOperation.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\n\n/// @notice Parameter struct for `ModifyLiquidity` pool operations\nstruct ModifyLiquidityParams {\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // how to modify the liquidity\n int256 liquidityDelta;\n // a value to set if you want unique liquidity positions at the same range\n bytes32 salt;\n}\n\n/// @notice Parameter struct for `Swap` pool operations\nstruct SwapParams {\n /// Whether to swap token0 for token1 or vice versa\n bool zeroForOne;\n /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n int256 amountSpecified;\n /// The sqrt price at which, if reached, the swap will stop executing\n uint160 sqrtPriceLimitX96;\n}\n" + }, + "contracts/admin/TimelockController.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2023-02-08\n*/\n\n//SPDX-License-Identifier: MIT\n\n// File @openzeppelin/contracts/access/IAccessControl.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(\n bytes32 indexed role,\n bytes32 indexed previousAdminRole,\n bytes32 indexed newAdminRole\n );\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(\n bytes32 indexed role,\n address indexed account,\n address indexed sender\n );\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n external\n view\n returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n\n// File @openzeppelin/contracts/utils/Context.sol@v4.8.1\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\n// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.8.1\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 IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n\n// File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.8.1\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n\n// File @openzeppelin/contracts/utils/math/Math.sol@v4.8.1\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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (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)\n internal\n pure\n returns (uint256)\n {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n\n// File @openzeppelin/contracts/utils/Strings.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\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)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _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\n// File @openzeppelin/contracts/access/AccessControl.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n interfaceId == type(IAccessControl).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role)\n public\n view\n virtual\n override\n returns (bytes32)\n {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account)\n public\n virtual\n override\n onlyRole(getRoleAdmin(role))\n {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account)\n public\n virtual\n override\n {\n require(\n account == _msgSender(),\n \"AccessControl: can only renounce roles for self\"\n );\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n// File @openzeppelin/contracts/utils/Address.sol@v4.8.1\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(\n address(this).balance >= amount,\n \"Address: insufficient balance\"\n );\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(\n success,\n \"Address: unable to send value, recipient may have reverted\"\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionCallWithValue(\n target,\n data,\n 0,\n \"Address: low-level call failed\"\n );\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\n functionCallWithValue(\n target,\n data,\n value,\n \"Address: low-level call with value failed\"\n );\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(\n address(this).balance >= value,\n \"Address: insufficient balance for call\"\n );\n (bool success, bytes memory returndata) = target.call{value: value}(\n data\n );\n return\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n view\n returns (bytes memory)\n {\n return\n functionStaticCall(\n target,\n data,\n \"Address: low-level static call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n internal\n returns (bytes memory)\n {\n return\n functionDelegateCall(\n target,\n data,\n \"Address: low-level delegate call failed\"\n );\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\n verifyCallResultFromTarget(\n target,\n success,\n returndata,\n errorMessage\n );\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)\n private\n pure\n {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n\n// File @openzeppelin/contracts/governance/TimelockController.sol@v4.8.1\n// OpenZeppelin Contracts (last updated v4.8.0) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is\n AccessControl,\n IERC721Receiver,\n IERC1155Receiver\n{\n bytes32 public constant TIMELOCK_ADMIN_ROLE =\n keccak256(\"TIMELOCK_ADMIN_ROLE\");\n bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n mapping(bytes32 => uint256) private _timestamps;\n uint256 private _minDelay;\n\n /**\n * @dev Emitted when a call is scheduled as part of operation `id`.\n */\n event CallScheduled(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data,\n bytes32 predecessor,\n uint256 delay\n );\n\n /**\n * @dev Emitted when a call is performed as part of operation `id`.\n */\n event CallExecuted(\n bytes32 indexed id,\n uint256 indexed index,\n address target,\n uint256 value,\n bytes data\n );\n\n /**\n * @dev Emitted when operation `id` is cancelled.\n */\n event Cancelled(bytes32 indexed id);\n\n /**\n * @dev Emitted when the minimum delay for future operations is modified.\n */\n event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n /**\n * @dev Initializes the contract with the following parameters:\n *\n * - `minDelay`: initial minimum delay for operations\n * - `proposers`: accounts to be granted proposer and canceller roles\n * - `executors`: accounts to be granted executor role\n * - `admin`: optional account to be granted admin role; disable with zero address\n *\n * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n * without being subject to delay, but this role should be subsequently renounced in favor of\n * administration through timelocked proposals. Previous versions of this contract would assign\n * this admin to the deployer automatically and should be renounced as well.\n */\n constructor(\n uint256 minDelay,\n address[] memory proposers,\n address[] memory executors,\n address admin\n ) {\n _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n // self administration\n _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n // optional admin\n if (admin != address(0)) {\n _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n }\n\n // register proposers and cancellers\n for (uint256 i = 0; i < proposers.length; ++i) {\n _setupRole(PROPOSER_ROLE, proposers[i]);\n _setupRole(CANCELLER_ROLE, proposers[i]);\n }\n\n // register executors\n for (uint256 i = 0; i < executors.length; ++i) {\n _setupRole(EXECUTOR_ROLE, executors[i]);\n }\n\n _minDelay = minDelay;\n emit MinDelayChange(0, minDelay);\n }\n\n /**\n * @dev Modifier to make a function callable only by a certain role. In\n * addition to checking the sender's role, `address(0)` 's role is also\n * considered. Granting a role to `address(0)` is equivalent to enabling\n * this role for everyone.\n */\n modifier onlyRoleOrOpenRole(bytes32 role) {\n if (!hasRole(role, address(0))) {\n _checkRole(role, _msgSender());\n }\n _;\n }\n\n /**\n * @dev Contract might receive/hold ETH as part of the maintenance process.\n */\n receive() external payable {}\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, AccessControl)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155Receiver).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns whether an id correspond to a registered operation. This\n * includes both Pending, Ready and Done operations.\n */\n function isOperation(bytes32 id)\n public\n view\n virtual\n returns (bool registered)\n {\n return getTimestamp(id) > 0;\n }\n\n /**\n * @dev Returns whether an operation is pending or not.\n */\n function isOperationPending(bytes32 id)\n public\n view\n virtual\n returns (bool pending)\n {\n return getTimestamp(id) > _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns whether an operation is ready or not.\n */\n function isOperationReady(bytes32 id)\n public\n view\n virtual\n returns (bool ready)\n {\n uint256 timestamp = getTimestamp(id);\n return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n }\n\n /**\n * @dev Returns whether an operation is done or not.\n */\n function isOperationDone(bytes32 id)\n public\n view\n virtual\n returns (bool done)\n {\n return getTimestamp(id) == _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Returns the timestamp at with an operation becomes ready (0 for\n * unset operations, 1 for done operations).\n */\n function getTimestamp(bytes32 id)\n public\n view\n virtual\n returns (uint256 timestamp)\n {\n return _timestamps[id];\n }\n\n /**\n * @dev Returns the minimum delay for an operation to become valid.\n *\n * This value can be changed by executing an operation that calls `updateDelay`.\n */\n function getMinDelay() public view virtual returns (uint256 duration) {\n return _minDelay;\n }\n\n /**\n * @dev Returns the identifier of an operation containing a single\n * transaction.\n */\n function hashOperation(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return keccak256(abi.encode(target, value, data, predecessor, salt));\n }\n\n /**\n * @dev Returns the identifier of an operation containing a batch of\n * transactions.\n */\n function hashOperationBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public pure virtual returns (bytes32 hash) {\n return\n keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n }\n\n /**\n * @dev Schedule an operation containing a single transaction.\n *\n * Emits a {CallScheduled} event.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function schedule(\n address target,\n uint256 value,\n bytes calldata data,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n bytes32 id = hashOperation(target, value, data, predecessor, salt);\n _schedule(id, delay);\n emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n }\n\n /**\n * @dev Schedule an operation containing a batch of transactions.\n *\n * Emits one {CallScheduled} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'proposer' role.\n */\n function scheduleBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt,\n uint256 delay\n ) public virtual onlyRole(PROPOSER_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n _schedule(id, delay);\n for (uint256 i = 0; i < targets.length; ++i) {\n emit CallScheduled(\n id,\n i,\n targets[i],\n values[i],\n payloads[i],\n predecessor,\n delay\n );\n }\n }\n\n /**\n * @dev Schedule an operation that is to becomes valid after a given delay.\n */\n function _schedule(bytes32 id, uint256 delay) private {\n require(\n !isOperation(id),\n \"TimelockController: operation already scheduled\"\n );\n require(\n delay >= getMinDelay(),\n \"TimelockController: insufficient delay\"\n );\n _timestamps[id] = block.timestamp + delay;\n }\n\n /**\n * @dev Cancel an operation.\n *\n * Requirements:\n *\n * - the caller must have the 'canceller' role.\n */\n function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n require(\n isOperationPending(id),\n \"TimelockController: operation cannot be cancelled\"\n );\n delete _timestamps[id];\n\n emit Cancelled(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a single transaction.\n *\n * Emits a {CallExecuted} event.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n // thus any modifications to the operation during reentrancy should be caught.\n // slither-disable-next-line reentrancy-eth\n function execute(\n address target,\n uint256 value,\n bytes calldata payload,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n _beforeCall(id, predecessor);\n _execute(target, value, payload);\n emit CallExecuted(id, 0, target, value, payload);\n _afterCall(id);\n }\n\n /**\n * @dev Execute an (ready) operation containing a batch of transactions.\n *\n * Emits one {CallExecuted} event per transaction in the batch.\n *\n * Requirements:\n *\n * - the caller must have the 'executor' role.\n */\n function executeBatch(\n address[] calldata targets,\n uint256[] calldata values,\n bytes[] calldata payloads,\n bytes32 predecessor,\n bytes32 salt\n ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n require(\n targets.length == values.length,\n \"TimelockController: length mismatch\"\n );\n require(\n targets.length == payloads.length,\n \"TimelockController: length mismatch\"\n );\n\n bytes32 id = hashOperationBatch(\n targets,\n values,\n payloads,\n predecessor,\n salt\n );\n\n _beforeCall(id, predecessor);\n for (uint256 i = 0; i < targets.length; ++i) {\n address target = targets[i];\n uint256 value = values[i];\n bytes calldata payload = payloads[i];\n _execute(target, value, payload);\n emit CallExecuted(id, i, target, value, payload);\n }\n _afterCall(id);\n }\n\n /**\n * @dev Execute an operation's call.\n */\n function _execute(\n address target,\n uint256 value,\n bytes calldata data\n ) internal virtual {\n (bool success, ) = target.call{value: value}(data);\n require(success, \"TimelockController: underlying transaction reverted\");\n }\n\n /**\n * @dev Checks before execution of an operation's calls.\n */\n function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n require(\n predecessor == bytes32(0) || isOperationDone(predecessor),\n \"TimelockController: missing dependency\"\n );\n }\n\n /**\n * @dev Checks after execution of an operation's calls.\n */\n function _afterCall(bytes32 id) private {\n require(\n isOperationReady(id),\n \"TimelockController: operation is not ready\"\n );\n _timestamps[id] = _DONE_TIMESTAMP;\n }\n\n /**\n * @dev Changes the minimum timelock duration for future operations.\n *\n * Emits a {MinDelayChange} event.\n *\n * Requirements:\n *\n * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n */\n function updateDelay(uint256 newDelay) external virtual {\n require(\n msg.sender == address(this),\n \"TimelockController: caller must be timelock\"\n );\n emit MinDelayChange(_minDelay, newDelay);\n _minDelay = newDelay;\n }\n\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155Received}.\n */\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155Received.selector;\n }\n\n /**\n * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n */\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] memory,\n uint256[] memory,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC1155BatchReceived.selector;\n }\n}" + }, + "contracts/CollateralManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType, ICollateralEscrowV1 } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IProtocolPausingManager.sol\";\nimport \"./interfaces/IHasProtocolPausingManager.sol\";\ncontract CollateralManager is OwnableUpgradeable, ICollateralManager {\n /* Storage */\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n ITellerV2 public tellerV2;\n address private collateralEscrowBeacon; // The address of the escrow contract beacon\n\n // bidIds -> collateralEscrow\n mapping(uint256 => address) public _escrows;\n // bidIds -> validated collateral info\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\n\n /**\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\n * that only a single tokenId per nft per loan can be collateralized.\n * Ex. Two bored apes cannot be used as collateral for a single loan.\n */\n struct CollateralInfo {\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\n mapping(address => Collateral) collateralInfo;\n }\n\n /* Events */\n event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);\n event CollateralCommitted(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralClaimed(uint256 _bidId);\n event CollateralDeposited(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n );\n event CollateralWithdrawn(\n uint256 _bidId,\n CollateralType _type,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId,\n address _recipient\n );\n\n /* Modifiers */\n modifier onlyTellerV2() {\n require(_msgSender() == address(tellerV2), \"Sender not authorized\");\n _;\n }\n\n modifier onlyProtocolOwner() {\n\n address protocolOwner = OwnableUpgradeable(address(tellerV2)).owner();\n\n require(_msgSender() == protocolOwner, \"Sender not authorized\");\n _;\n }\n\n modifier whenProtocolNotPaused() { \n address pausingManager = IHasProtocolPausingManager( address(tellerV2) ).getProtocolPausingManager();\n\n require( IProtocolPausingManager(address(pausingManager)).protocolPaused() == false , \"Protocol is paused\");\n _;\n }\n\n /* External Functions */\n\n /**\n * @notice Initializes the collateral manager.\n * @param _collateralEscrowBeacon The address of the escrow implementation.\n * @param _tellerV2 The address of the protocol.\n */\n function initialize(address _collateralEscrowBeacon, address _tellerV2)\n external\n initializer\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n tellerV2 = ITellerV2(_tellerV2);\n __Ownable_init_unchained();\n }\n\n /**\n * @notice Sets the address of the Beacon contract used for the collateral escrow contracts.\n * @param _collateralEscrowBeacon The address of the Beacon contract.\n */\n function setCollateralEscrowBeacon(address _collateralEscrowBeacon)\n external\n onlyProtocolOwner\n {\n collateralEscrowBeacon = _collateralEscrowBeacon;\n }\n\n /**\n * @notice Checks to see if a bid is backed by collateral.\n * @param _bidId The id of the bid to check.\n */\n\n function isBidCollateralBacked(uint256 _bidId)\n public\n virtual\n returns (bool)\n {\n return _bidCollaterals[_bidId].collateralAddresses.length() > 0;\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral assets.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n (validation_, ) = checkBalances(borrower, _collateralInfo);\n\n //if the collateral info is valid, call commitCollateral for each one\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n }\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 ) public onlyTellerV2 returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n require(borrower != address(0), \"Loan has no borrower\");\n validation_ = _checkBalance(borrower, _collateralInfo);\n if (validation_) {\n _commitCollateral(_bidId, _collateralInfo);\n }\n }\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)\n external\n returns (bool validation_)\n {\n Collateral[] memory collateralInfos = getCollateralInfo(_bidId);\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = _checkBalances(borrower, collateralInfos, true);\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n */\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) public returns (bool validated_, bool[] memory checks_) {\n return _checkBalances(_borrowerAddress, _collateralInfo, false);\n }\n\n /**\n * @notice Deploys a new collateral escrow and deposits collateral.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {\n if (isBidCollateralBacked(_bidId)) {\n //attempt deploy a new collateral escrow contract if there is not already one. Otherwise fetch it.\n (address proxyAddress, ) = _deployEscrow(_bidId);\n _escrows[_bidId] = proxyAddress;\n\n //for each bid collateral associated with this loan, deposit the collateral into escrow\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n _deposit(\n _bidId,\n _bidCollaterals[_bidId].collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ]\n );\n }\n\n emit CollateralEscrowDeployed(_bidId, proxyAddress);\n }\n }\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 return _escrows[_bidId];\n }\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 infos_ The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n public\n view\n returns (Collateral[] memory infos_)\n {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n address[] memory collateralAddresses = collateral\n .collateralAddresses\n .values();\n infos_ = new Collateral[](collateralAddresses.length);\n for (uint256 i; i < collateralAddresses.length; i++) {\n infos_[i] = collateral.collateralInfo[collateralAddresses[i]];\n }\n }\n\n /**\n * @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.\n * @param _bidId The ID of a bid on TellerV2.\n * @param _collateralAddress An address used as collateral.\n * @return amount_ The amount of collateral of type _collateralAddress.\n */\n function getCollateralAmount(uint256 _bidId, address _collateralAddress)\n public\n view\n returns (uint256 amount_)\n {\n amount_ = _bidCollaterals[_bidId]\n .collateralInfo[_collateralAddress]\n ._amount;\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external whenProtocolNotPaused {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(bidState == BidState.PAID, \"collateral cannot be withdrawn\");\n\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\n\n emit CollateralClaimed(_bidId);\n }\n\n function withdrawDustTokens(\n uint256 _bidId, \n address _tokenAddress, \n uint256 _amount,\n address _recipientAddress\n ) external onlyProtocolOwner whenProtocolNotPaused {\n\n ICollateralEscrowV1(_escrows[_bidId]).withdrawDustTokens(\n _tokenAddress,\n _amount,\n _recipientAddress\n );\n }\n\n\n function getCollateralEscrowBeacon() external view returns (address) {\n\n return collateralEscrowBeacon;\n\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateral(uint256 _bidId) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\n emit CollateralClaimed(_bidId);\n }\n }\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been CLOSED after being defaulted.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external onlyTellerV2 whenProtocolNotPaused {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n\n require(\n bidState == BidState.CLOSED,\n \"Loan has not been liquidated\"\n );\n\n _withdraw(_bidId, _collateralRecipient);\n emit CollateralClaimed(_bidId);\n }\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 onlyTellerV2\n whenProtocolNotPaused\n {\n if (isBidCollateralBacked(_bidId)) {\n BidState bidState = tellerV2.getBidState(_bidId);\n require(\n bidState == BidState.LIQUIDATED,\n \"Loan has not been liquidated\"\n );\n _withdraw(_bidId, _liquidatorAddress);\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function _deployEscrow(uint256 _bidId)\n internal\n virtual\n returns (address proxyAddress_, address borrower_)\n {\n proxyAddress_ = _escrows[_bidId];\n // Get bid info\n borrower_ = tellerV2.getLoanBorrower(_bidId);\n if (proxyAddress_ == address(0)) {\n require(borrower_ != address(0), \"Bid does not exist\");\n\n BeaconProxy proxy = new BeaconProxy(\n collateralEscrowBeacon,\n abi.encodeWithSelector(\n ICollateralEscrowV1.initialize.selector,\n _bidId\n )\n );\n proxyAddress_ = address(proxy);\n }\n }\n\n /*\n * @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n * @param collateralInfo The collateral info to deposit.\n\n */\n function _deposit(uint256 _bidId, Collateral memory collateralInfo)\n internal\n virtual\n {\n require(collateralInfo._amount > 0, \"Collateral not validated\");\n (address escrowAddress, address borrower) = _deployEscrow(_bidId);\n ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(\n escrowAddress\n );\n // Pull collateral from borrower & deposit into escrow\n if (collateralInfo._collateralType == CollateralType.ERC20) {\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._amount\n );\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._amount\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC20,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n 0\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC721) {\n IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId\n );\n IERC721Upgradeable(collateralInfo._collateralAddress).approve(\n escrowAddress,\n collateralInfo._tokenId\n );\n collateralEscrow.depositAsset(\n CollateralType.ERC721,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else if (collateralInfo._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .safeTransferFrom(\n borrower,\n address(this),\n collateralInfo._tokenId,\n collateralInfo._amount,\n data\n );\n IERC1155Upgradeable(collateralInfo._collateralAddress)\n .setApprovalForAll(escrowAddress, true);\n collateralEscrow.depositAsset(\n CollateralType.ERC1155,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n } else {\n revert(\"Unexpected collateral type\");\n }\n emit CollateralDeposited(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Withdraws collateral to a given receiver's address.\n * @param _bidId The id of the bid to withdraw collateral for.\n * @param _receiver The address to withdraw the collateral to.\n */\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\n for (\n uint256 i;\n i < _bidCollaterals[_bidId].collateralAddresses.length();\n i++\n ) {\n // Get collateral info\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\n .collateralInfo[\n _bidCollaterals[_bidId].collateralAddresses.at(i)\n ];\n // Withdraw collateral from escrow and send it to bid lender\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n _receiver\n );\n emit CollateralWithdrawn(\n _bidId,\n collateralInfo._collateralType,\n collateralInfo._collateralAddress,\n collateralInfo._amount,\n collateralInfo._tokenId,\n _receiver\n );\n }\n }\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 */\n function _commitCollateral(\n uint256 _bidId,\n Collateral memory _collateralInfo\n ) internal virtual {\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\n\n require(\n !collateral.collateralAddresses.contains(\n _collateralInfo._collateralAddress\n ),\n \"Cannot commit multiple collateral with the same address\"\n );\n require(\n _collateralInfo._collateralType != CollateralType.ERC721 ||\n _collateralInfo._amount == 1,\n \"ERC721 collateral must have amount of 1\"\n );\n\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\n collateral.collateralInfo[\n _collateralInfo._collateralAddress\n ] = _collateralInfo;\n emit CollateralCommitted(\n _bidId,\n _collateralInfo._collateralType,\n _collateralInfo._collateralAddress,\n _collateralInfo._amount,\n _collateralInfo._tokenId\n );\n }\n\n /**\n * @notice Checks the validity of a borrower's multiple collateral balances.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral assets.\n * @param _shortCircut if true, will return immediately until an invalid balance\n */\n function _checkBalances(\n address _borrowerAddress,\n Collateral[] memory _collateralInfo,\n bool _shortCircut\n ) internal virtual returns (bool validated_, bool[] memory checks_) {\n checks_ = new bool[](_collateralInfo.length);\n validated_ = true;\n for (uint256 i; i < _collateralInfo.length; i++) {\n bool isValidated = _checkBalance(\n _borrowerAddress,\n _collateralInfo[i]\n );\n checks_[i] = isValidated;\n if (!isValidated) {\n validated_ = false;\n //if short circuit is true, return on the first invalid balance to save execution cycles. Values of checks[] will be invalid/undetermined if shortcircuit is true.\n if (_shortCircut) {\n return (validated_, checks_);\n }\n }\n }\n }\n\n /**\n * @notice Checks the validity of a borrower's single collateral balance.\n * @param _borrowerAddress The address of the borrower holding the collateral.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balances were validated.\n */\n function _checkBalance(\n address _borrowerAddress,\n Collateral memory _collateralInfo\n ) internal virtual returns (bool) {\n CollateralType collateralType = _collateralInfo._collateralType;\n\n if (collateralType == CollateralType.ERC20) {\n return\n _collateralInfo._amount <=\n IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(\n _borrowerAddress\n );\n } else if (collateralType == CollateralType.ERC721) {\n return\n _borrowerAddress ==\n IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(\n _collateralInfo._tokenId\n );\n } else if (collateralType == CollateralType.ERC1155) {\n return\n _collateralInfo._amount <=\n IERC1155Upgradeable(_collateralInfo._collateralAddress)\n .balanceOf(_borrowerAddress, _collateralInfo._tokenId);\n } else {\n return false;\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/deprecated/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/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/EAS/TellerASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations.\n */\ncontract TellerASEIP712Verifier is IEASEIP712Verifier {\n error InvalidSignature();\n\n string public constant VERSION = \"0.8\";\n\n // EIP712 domain separator, making signatures from different domains incompatible.\n bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase\n\n // The hash of the data type used to relay calls to the attest function. It's the value of\n // keccak256(\"Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)\").\n bytes32 public constant ATTEST_TYPEHASH =\n 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;\n\n // The hash of the data type used to relay calls to the revoke function. It's the value of\n // keccak256(\"Revoke(bytes32 uuid,uint256 nonce)\").\n bytes32 public constant REVOKE_TYPEHASH =\n 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;\n\n // Replay protection nonces.\n mapping(address => uint256) private _nonces;\n\n /**\n * @dev Creates a new EIP712Verifier instance.\n */\n constructor() {\n uint256 chainId;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"EAS\")),\n keccak256(bytes(VERSION)),\n chainId,\n address(this)\n )\n );\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function getNonce(address account)\n external\n view\n override\n returns (uint256)\n {\n return _nonces[account];\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\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 override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n ATTEST_TYPEHASH,\n recipient,\n schema,\n expirationTime,\n refUUID,\n keccak256(data),\n _nonces[attester]++\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n\n /**\n * @inheritdoc IEASEIP712Verifier\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++)\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n if (recoveredAddress == address(0) || recoveredAddress != attester) {\n revert InvalidSignature();\n }\n }\n}\n" + }, + "contracts/EAS/TellerASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title The global AS registry.\n */\ncontract TellerASRegistry is IASRegistry {\n error AlreadyExists();\n\n string public constant VERSION = \"0.8\";\n\n // The global mapping between AS records and their IDs.\n mapping(bytes32 => ASRecord) private _registry;\n\n // The global counter for the total number of attestations.\n uint256 private _asCount;\n\n /**\n * @inheritdoc IASRegistry\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n override\n returns (bytes32)\n {\n uint256 index = ++_asCount;\n\n ASRecord memory asRecord = ASRecord({\n uuid: EMPTY_UUID,\n index: index,\n schema: schema,\n resolver: resolver\n });\n\n bytes32 uuid = _getUUID(asRecord);\n if (_registry[uuid].uuid != EMPTY_UUID) {\n revert AlreadyExists();\n }\n\n asRecord.uuid = uuid;\n _registry[uuid] = asRecord;\n\n emit Registered(uuid, index, schema, resolver, msg.sender);\n\n return uuid;\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getAS(bytes32 uuid)\n external\n view\n override\n returns (ASRecord memory)\n {\n return _registry[uuid];\n }\n\n /**\n * @inheritdoc IASRegistry\n */\n function getASCount() external view override returns (uint256) {\n return _asCount;\n }\n\n /**\n * @dev Calculates a UUID for a given AS.\n *\n * @param asRecord The input AS.\n *\n * @return AS UUID.\n */\n function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) {\n return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver));\n }\n}\n" + }, + "contracts/EAS/TellerASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IASResolver.sol\";\n\n/**\n * @title A base resolver contract\n */\nabstract contract TellerASResolver is IASResolver {\n error NotPayable();\n\n function isPayable() public pure virtual override returns (bool) {\n return false;\n }\n\n receive() external payable virtual {\n if (!isPayable()) {\n revert NotPayable();\n }\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/escrow/CollateralEscrowV1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n// Interfaces\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\ncontract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\n uint256 public bidId;\n /* Mappings */\n mapping(address => Collateral) public collateralBalances; // collateral address -> collateral\n\n /* Events */\n event CollateralDeposited(address _collateralAddress, uint256 _amount);\n event CollateralWithdrawn(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n );\n\n /**\n * @notice Initializes an escrow.\n * @notice The id of the associated bid.\n */\n function initialize(uint256 _bidId) public initializer {\n __Ownable_init();\n bidId = _bidId;\n }\n\n /**\n * @notice Returns the id of the associated bid.\n * @return The id of the associated bid.\n */\n function getBid() external view returns (uint256) {\n return bidId;\n }\n\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.\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 virtual onlyOwner {\n require(_amount > 0, \"Deposit amount cannot be zero\");\n _depositCollateral(\n _collateralType,\n _collateralAddress,\n _amount,\n _tokenId\n );\n Collateral storage collateral = collateralBalances[_collateralAddress];\n\n //Avoids asset overwriting. Can get rid of this restriction by restructuring collateral balances storage so it isnt a mapping based on address.\n require(\n collateral._amount == 0,\n \"Unable to deposit multiple collateral asset instances of the same contract address.\"\n );\n\n collateral._collateralType = _collateralType;\n collateral._amount = _amount;\n collateral._tokenId = _tokenId;\n emit CollateralDeposited(_collateralAddress, _amount);\n }\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 virtual onlyOwner {\n require(_amount > 0, \"Withdraw amount cannot be zero\");\n Collateral storage collateral = collateralBalances[_collateralAddress];\n require(\n collateral._amount >= _amount,\n \"No collateral balance for asset\"\n );\n _withdrawCollateral(\n collateral,\n _collateralAddress,\n _amount,\n _recipient\n );\n collateral._amount -= _amount;\n emit CollateralWithdrawn(_collateralAddress, _amount, _recipient);\n }\n\n function withdrawDustTokens( \n address tokenAddress, \n uint256 amount,\n address recipient\n ) external virtual onlyOwner { //the owner should be collateral manager \n \n require(tokenAddress != address(0), \"Invalid token address\");\n\n Collateral storage collateral = collateralBalances[tokenAddress];\n require(\n collateral._amount == 0,\n \"Asset not allowed to be withdrawn as dust\"\n ); \n \n \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress),recipient, amount); \n\n \n }\n\n\n /**\n * @notice Internal function for transferring collateral assets into this contract.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to deposit.\n * @param _tokenId The token id of the collateral asset.\n */\n function _depositCollateral(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) internal {\n // Deposit ERC20\n if (_collateralType == CollateralType.ERC20) {\n SafeERC20Upgradeable.safeTransferFrom(\n IERC20Upgradeable(_collateralAddress),\n _msgSender(),\n address(this),\n _amount\n );\n }\n // Deposit ERC721\n else if (_collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect deposit amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n _msgSender(),\n address(this),\n _tokenId\n );\n }\n // Deposit ERC1155\n else if (_collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n _msgSender(),\n address(this),\n _tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n /**\n * @notice Internal function for transferring collateral assets out of this contract.\n * @param _collateral The collateral asset to withdraw.\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 _withdrawCollateral(\n Collateral memory _collateral,\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) internal {\n // Withdraw ERC20\n if (_collateral._collateralType == CollateralType.ERC20) { \n SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_collateralAddress),_recipient, _amount); \n }\n // Withdraw ERC721\n else if (_collateral._collateralType == CollateralType.ERC721) {\n require(_amount == 1, \"Incorrect withdrawal amount\");\n IERC721Upgradeable(_collateralAddress).transferFrom(\n address(this),\n _recipient,\n _collateral._tokenId\n );\n }\n // Withdraw ERC1155\n else if (_collateral._collateralType == CollateralType.ERC1155) {\n bytes memory data;\n\n IERC1155Upgradeable(_collateralAddress).safeTransferFrom(\n address(this),\n _recipient,\n _collateral._tokenId,\n _amount,\n data\n );\n } else {\n revert(\"Invalid collateral type\");\n }\n }\n\n // On NFT Received handlers\n\n function onERC721Received(address, address, uint256, bytes calldata)\n external\n pure\n returns (bytes4)\n {\n return\n bytes4(\n keccak256(\"onERC721Received(address,address,uint256,bytes)\")\n );\n }\n\n function onERC1155Received(\n address,\n address,\n uint256 id,\n uint256 value,\n bytes calldata\n ) external returns (bytes4) {\n return\n bytes4(\n keccak256(\n \"onERC1155Received(address,address,uint256,uint256,bytes)\"\n )\n );\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata\n ) external returns (bytes4) {\n require(\n _ids.length == 1,\n \"Only allowed one asset batch transfer per transaction.\"\n );\n return\n bytes4(\n keccak256(\n \"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"\n )\n );\n }\n}\n" + }, + "contracts/EscrowVault.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n/*\nAn escrow vault for repayments \n*/\n\n// Contracts\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IEscrowVault.sol\";\n\ncontract EscrowVault is Initializable, ContextUpgradeable, IEscrowVault {\n using SafeERC20 for ERC20;\n\n //account => token => balance\n mapping(address => mapping(address => uint256)) public balances;\n\n constructor() {}\n\n function initialize() external initializer {}\n\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The id for the loan to set.\n * @param token The address of the new active lender.\n */\n function deposit(address account, address token, uint256 amount)\n public\n override\n {\n uint256 balanceBefore = ERC20(token).balanceOf(address(this));\n ERC20(token).safeTransferFrom(_msgSender(), address(this), amount);\n uint256 balanceAfter = ERC20(token).balanceOf(address(this));\n\n balances[account][token] += balanceAfter - balanceBefore; //used for fee-on-transfer tokens\n }\n\n function withdraw(address token, uint256 amount) external {\n address account = _msgSender();\n\n balances[account][token] -= amount;\n ERC20(token).safeTransfer(account, amount);\n }\n}\n" + }, + "contracts/interfaces/aave/DataTypes.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62: siloed borrowing enabled\n //bit 63: flashloaning enabled\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n" + }, + "contracts/interfaces/aave/IFlashLoanSimpleReceiver.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { IPool } from \"./IPool.sol\";\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed asset\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param asset The address of the flash-borrowed asset\n * @param amount The amount of the flash-borrowed asset\n * @param premium The fee of the flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address asset,\n uint256 amount,\n uint256 premium,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n function POOL() external view returns (IPool);\n}\n" + }, + "contracts/interfaces/aave/IPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport { IPoolAddressesProvider } from \"./IPoolAddressesProvider.sol\";\nimport { DataTypes } from \"./DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n */\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n */\n event BackUnbacked(\n address indexed reserve,\n address indexed backer,\n uint256 amount,\n uint256 fee\n );\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n */\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n */\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n */\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n */\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(\n address indexed asset,\n uint256 totalDebt\n );\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n */\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n */\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n */\n event RebalanceStableBorrowRate(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n */\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n */\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n */\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n * @return The backed amount\n */\n function backUnbacked(address asset, uint256 amount, uint256 fee)\n external\n returns (uint256);\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n */\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n */\n function withdraw(address asset, uint256 amount, address to)\n external\n returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n */\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n */\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n */\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n */\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n */\n function swapBorrowRateMode(address asset, uint256 interestRateMode)\n external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n */\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n */\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n */\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://docs.aave.com/developers/\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n */\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n */\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n */\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n */\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n */\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n */\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n */\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n * moment (approx. a borrower would get if opening a position). This means that is always used in\n * combination with variable debt supply/balances.\n * If using this function externally, consider that is possible to have an increasing normalized\n * variable debt that is not equivalent to how the variable debt index would be updated in storage\n * (e.g. only updates with non-zero variable debt supply)\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n */\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n */\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n */\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(\n uint8 id,\n DataTypes.EModeCategory memory config\n ) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id)\n external\n view\n returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT()\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n */\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(address token, address to, uint256 amount) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n */\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" + }, + "contracts/interfaces/aave/IPoolAddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n */\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n */\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n */\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n */\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n */\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n */\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n */\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n */\n function setPoolDataProvider(address newDataProvider) external;\n}\n" + }, + "contracts/interfaces/defi/IAerodromePool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAerodromePool\n * @notice Defines the basic interface for an Aerodrome Pool.\n */\ninterface IAerodromePool {\n function lastObservation() external view returns (uint256, uint256, uint256);\n function observationLength() external view returns (uint256 );\n\n function observations(uint256 ticks) external view returns (uint256, uint256, uint256);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n}\n" + }, + "contracts/interfaces/defi/IAlgebraPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IAlgebraPool\n * @notice Interface for Algebra V1 pools (used by Camelot V3 on ApeChain).\n * Algebra pools use globalState() and getTimepoints() instead of\n * Uniswap V3's slot0() and observe().\n */\ninterface IAlgebraPool {\n function token0() external view returns (address);\n function token1() external view returns (address);\n\n function globalState() external view returns (\n uint160 price,\n int24 tick,\n uint16 feeZto,\n uint16 feeOtz,\n uint16 timepointIndex,\n uint8 communityFeeToken0,\n uint8 communityFeeToken1,\n bool unlocked\n );\n\n function getTimepoints(uint32[] calldata secondsAgos) external view returns (\n int56[] memory tickCumulatives,\n uint160[] memory secondsPerLiquidityCumulatives\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/ICommitmentRolloverLoan.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ICommitmentRolloverLoan {\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\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/IERC4626.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \ninterface IERC4626 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when assets are deposited into the vault.\n * @param caller The caller who deposited the assets.\n * @param owner The owner who will receive the shares.\n * @param assets The amount of assets deposited.\n * @param shares The amount of shares minted.\n */\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n /**\n * @dev Emitted when shares are withdrawn from the vault.\n * @param caller The caller who withdrew the assets.\n * @param receiver The receiver of the assets.\n * @param owner The owner whose shares were burned.\n * @param assets The amount of assets withdrawn.\n * @param shares The amount of shares burned.\n */\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n METADATA\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the address of the underlying token used for the vault.\n * @return The address of the underlying asset token.\n */\n function asset() external view returns (address);\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Deposits assets into the vault and mints shares to the receiver.\n * @param assets The amount of assets to deposit.\n * @param receiver The address that will receive the shares.\n * @return shares The amount of shares minted.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Mints shares to the receiver by depositing exactly amount of assets.\n * @param shares The amount of shares to mint.\n * @param receiver The address that will receive the shares.\n * @return assets The amount of assets deposited.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Withdraws assets from the vault to the receiver by burning shares from owner.\n * @param assets The amount of assets to withdraw.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return shares The amount of shares burned.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets to receiver.\n * @param shares The amount of shares to burn.\n * @param receiver The address that will receive the assets.\n * @param owner The address whose shares will be burned.\n * @return assets The amount of assets sent to the receiver.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Returns the total amount of assets managed by the vault.\n * @return The total amount of assets.\n */\n function totalAssets() external view returns (uint256);\n\n /**\n * @dev Calculates the amount of shares that would be minted for a given amount of assets.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares.\n * @param shares The amount of shares to burn.\n * @return assets The amount of assets that would be withdrawn.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxAssets The maximum amount of assets that can be deposited.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions.\n * @param assets The amount of assets to deposit.\n * @return shares The amount of shares that would be minted.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be minted for a specific receiver.\n * @param receiver The address of the receiver.\n * @return maxShares The maximum amount of shares that can be minted.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a mint at the current block, given current on-chain conditions.\n * @param shares The amount of shares to mint.\n * @return assets The amount of assets that would be deposited.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner.\n * @param owner The address of the owner.\n * @return maxAssets The maximum amount of assets that can be withdrawn.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions.\n * @param assets The amount of assets to withdraw.\n * @return shares The amount of shares that would be burned.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner.\n * @param owner The address of the owner.\n * @return maxShares The maximum amount of shares that can be redeemed.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions.\n * @param shares The amount of shares to redeem.\n * @return assets The amount of assets that would be withdrawn.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\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/IFlashRolloverLoan_G6.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G6 {\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/IFlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan {\n struct RolloverCallbackArgs { \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.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_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V2 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n )\n external\n ;\n\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/ILenderCommitmentGroup_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup_V3 {\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; \n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n\n )\n external\n ;\n\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/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/ILenderCommitmentGroupSharesIntegrated.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n \ninterface ILenderCommitmentGroupSharesIntegrated is IERC20 {\n\n\n \n function initialize( ) external ; \n\n\n function mint(address _recipient, uint256 _amount ) external ;\n function burn(address _burner, uint256 _amount ) external ;\n\n function getSharesLastTransferredAt(address owner ) external view returns (uint256) ;\n\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/IMarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IMarketLiquidityRewards {\n struct RewardAllocation {\n address allocator;\n address rewardTokenAddress;\n uint256 rewardTokenAmount;\n uint256 marketId;\n //requirements for loan\n address requiredPrincipalTokenAddress; //0 for any\n address requiredCollateralTokenAddress; //0 for any -- could be an enumerable set?\n uint256 minimumCollateralPerPrincipalAmount;\n uint256 rewardPerLoanPrincipalAmount;\n uint32 bidStartTimeMin;\n uint32 bidStartTimeMax;\n AllocationStrategy allocationStrategy;\n }\n\n enum AllocationStrategy {\n BORROWER,\n LENDER\n }\n\n function allocateRewards(RewardAllocation calldata _allocation)\n external\n returns (uint256 allocationId_);\n\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) external;\n\n function deallocateRewards(uint256 _allocationId, uint256 _amount) external;\n\n function claimRewards(uint256 _allocationId, uint256 _bidId) external;\n\n function rewardClaimedForBid(uint256 _bidId, uint256 _allocationId)\n external\n view\n returns (bool);\n\n function getRewardTokenAmount(uint256 _allocationId)\n external\n view\n returns (uint256);\n\n function initialize() 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/IPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IPriceAdapter {\n \n function registerPriceRoute(bytes memory route) external returns (bytes32);\n\n function getPriceRatioQ96( bytes32 route ) external view returns( uint256 );\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 \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/ITellerV2Autopay.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Autopay {\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external;\n\n function autoPayLoanMinimum(uint256 _bidId) external;\n\n function initialize(uint16 _newFee, address _newOwner) external;\n\n function setAutopayFee(uint16 _newFee) external;\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/IUniswapV2Router.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n @notice This interface defines the different functions available for a UniswapV2Router.\n @author develop@teller.finance\n */\ninterface IUniswapV2Router {\n function factory() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB)\n external\n pure\n returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n /**\n @notice It returns the address of the canonical WETH address;\n */\n function WETH() external pure returns (address);\n\n /**\n @notice Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountIn The amount of input tokens to send.\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the ETH.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n @dev If the to address is a smart contract, it must have the ability to receive ETH.\n */\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /**\n @notice Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist).\n @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.\n @param to Recipient of the output tokens.\n @param deadline Unix timestamp after which the transaction will revert.\n @return amounts The input token amount and all subsequent output token amounts.\n */\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n}\n" + }, + "contracts/interfaces/IWETH.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @notice It is the interface of functions that we use for the canonical WETH contract.\n *\n * @author develop@teller.finance\n */\ninterface IWETH {\n /**\n * @notice It withdraws ETH from the contract by sending it to the caller and reducing the caller's internal balance of WETH.\n * @param amount The amount of ETH to withdraw.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice It deposits ETH into the contract and increases the caller's internal balance of WETH.\n */\n function deposit() external payable;\n\n /**\n * @notice It gets the ETH deposit balance of an {account}.\n * @param account Address to get balance of.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice It transfers the WETH amount specified to the given {account}.\n * @param to Address to transfer to\n * @param value Amount of WETH to transfer\n */\n function transfer(address to, uint256 value) external returns (bool);\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/IUniswapV2Pair.sol": { + "content": "pragma solidity >=0.8.0;\n\ninterface IUniswapV2Pair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n function factory() external view returns (address);\n function token0() external view returns (address);\n function token1() external view returns (address);\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n function price0CumulativeLast() external view returns (uint);\n function price1CumulativeLast() external view returns (uint);\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n function burn(address to) external returns (uint amount0, uint amount1);\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n function skim(address to) external;\n function sync() external;\n\n function initialize(address, address) external;\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/IUniswapV4Pool.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 IUniswapV4Pool 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/interfaces/uniswapv4/IImmutableState.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\n\n/// @title IImmutableState\n/// @notice Interface for the ImmutableState contract\ninterface IImmutableState {\n /// @notice The Uniswap v4 PoolManager contract\n function poolManager() external view returns (IPoolManager);\n}" + }, + "contracts/interfaces/uniswapv4/IStateView.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {PoolId} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {Position} from \"@uniswap/v4-core/src/libraries/Position.sol\";\nimport {IImmutableState} from \"./IImmutableState.sol\";\n\n/// @title IStateView\n/// @notice Interface for the StateView contract\ninterface IStateView is IImmutableState {\n /// @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n /// @dev Corresponds to pools[poolId].slot0\n /// @param poolId The ID of the pool.\n /// @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n /// @return tick The current tick of the pool.\n /// @return protocolFee The protocol fee of the pool.\n /// @return lpFee The swap fee of the pool.\n function getSlot0(PoolId poolId)\n external\n view\n returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);\n\n /// @notice Retrieves the tick information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve information for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickInfo(PoolId poolId, int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128\n );\n\n /// @notice Retrieves the liquidity information of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve liquidity for.\n /// @return liquidityGross The total position liquidity that references this tick\n /// @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function getTickLiquidity(PoolId poolId, int24 tick)\n external\n view\n returns (uint128 liquidityGross, int128 liquidityNet);\n\n /// @notice Retrieves the fee growth outside a tick range of a pool\n /// @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve fee growth for.\n /// @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n /// @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n function getTickFeeGrowthOutside(PoolId poolId, int24 tick)\n external\n view\n returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128);\n\n /// @notice Retrieves the global fee growth of a pool.\n /// @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n /// @param poolId The ID of the pool.\n /// @return feeGrowthGlobal0 The global fee growth for token0.\n /// @return feeGrowthGlobal1 The global fee growth for token1.\n function getFeeGrowthGlobals(PoolId poolId)\n external\n view\n returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1);\n\n /// @notice Retrieves the total liquidity of a pool.\n /// @dev Corresponds to pools[poolId].liquidity\n /// @param poolId The ID of the pool.\n /// @return liquidity The liquidity of the pool.\n function getLiquidity(PoolId poolId) external view returns (uint128 liquidity);\n\n /// @notice Retrieves the tick bitmap of a pool at a specific tick.\n /// @dev Corresponds to pools[poolId].tickBitmap[tick]\n /// @param poolId The ID of the pool.\n /// @param tick The tick to retrieve the bitmap for.\n /// @return tickBitmap The bitmap of the tick.\n function getTickBitmap(PoolId poolId, int16 tick) external view returns (uint256 tickBitmap);\n\n /// @notice Retrieves the position info without needing to calculate the `positionId`.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param owner The owner of the liquidity position.\n /// @param tickLower The lower tick of the liquidity range.\n /// @param tickUpper The upper tick of the liquidity range.\n /// @param salt The bytes32 randomness to further distinguish position state.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the position information of a pool at a specific position ID.\n /// @dev Corresponds to pools[poolId].positions[positionId]\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n /// @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n /// @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n function getPositionInfo(PoolId poolId, bytes32 positionId)\n external\n view\n returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128);\n\n /// @notice Retrieves the liquidity of a position.\n /// @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieving liquidity as compared to getPositionInfo\n /// @param poolId The ID of the pool.\n /// @param positionId The ID of the position.\n /// @return liquidity The liquidity of the position.\n function getPositionLiquidity(PoolId poolId, bytes32 positionId) external view returns (uint128 liquidity);\n\n /// @notice Calculate the fee growth inside a tick range of a pool\n /// @dev pools[poolId].feeGrowthInside0LastX128 in Position.Info is cached and can become stale. This function will calculate the up to date feeGrowthInside\n /// @param poolId The ID of the pool.\n /// @param tickLower The lower tick of the range.\n /// @param tickUpper The upper tick of the range.\n /// @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n /// @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n function getFeeGrowthInside(PoolId poolId, int24 tickLower, int24 tickUpper)\n external\n view\n returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128);\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_Factory_V2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V2 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V2.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V2.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory_V3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \n import { IERC4626 } from \"../../../interfaces/IERC4626.sol\";\n\nimport { ILenderCommitmentGroup_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\n \n\ncontract LenderCommitmentGroupFactory_V3 is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n \n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _priceAdapterAddress Address for the pool price adapter\n * @param _priceAdapterRoute Encoded roue for the price adapter \n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup_V3.CommitmentGroupConfig calldata _commitmentGroupConfig,\n address _priceAdapterAddress, \n bytes calldata _priceAdapterRoute\n ) external returns ( address ) {\n \n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup_V3.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _priceAdapterAddress,\n _priceAdapterRoute\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n \n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _depositPrincipal(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n \n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _depositPrincipal( \n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = IERC4626( address(_newGroupContract) )\n .deposit(\n _initialPrincipalAmount,\n sharesRecipient \n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Factory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \n\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 \"../../../libraries/NumbersLib.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\n \nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\n\ncontract LenderCommitmentGroupFactory is OwnableUpgradeable {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n \n //this is the beacon proxy\n address public lenderGroupBeacon;\n\n\n mapping(address => uint256) public deployedLenderGroupContracts;\n\n event DeployedLenderGroupContract(address indexed groupContract);\n\n \n\n /**\n * @notice Initializes the factory contract.\n * @param _lenderGroupBeacon The address of the beacon proxy used for deploying group contracts.\n */\n function initialize(address _lenderGroupBeacon )\n external\n initializer\n {\n lenderGroupBeacon = _lenderGroupBeacon; \n __Ownable_init_unchained();\n }\n\n\n /**\n * @notice Deploys a new lender commitment group pool contract.\n * @dev The function initializes the deployed contract and optionally adds an initial principal amount.\n * @param _initialPrincipalAmount The initial principal amount to be deposited into the group contract.\n * @param _commitmentGroupConfig Configuration parameters for the lender commitment group.\n * @param _poolOracleRoutes Array of pool route configurations for the Uniswap pricing library.\n * @return newGroupContract_ Address of the newly deployed group contract.\n */\n function deployLenderCommitmentGroupPool(\n uint256 _initialPrincipalAmount,\n ILenderCommitmentGroup.CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external returns ( address ) {\n \n\n \n BeaconProxy newGroupContract_ = new BeaconProxy(\n lenderGroupBeacon,\n abi.encodeWithSelector(\n ILenderCommitmentGroup.initialize.selector, //this initializes \n _commitmentGroupConfig,\n _poolOracleRoutes\n\n )\n );\n\n deployedLenderGroupContracts[address(newGroupContract_)] = block.number; //consider changing this ?\n emit DeployedLenderGroupContract(address(newGroupContract_));\n\n\n\n //it is not absolutely necessary to have this call here but it allows the user to potentially save a tx step so it is nice to have .\n if (_initialPrincipalAmount > 0) {\n _addPrincipalToCommitmentGroup(\n address(newGroupContract_),\n _initialPrincipalAmount,\n _commitmentGroupConfig.principalTokenAddress \n \n ); \n } \n\n\n //transfer ownership to msg.sender \n OwnableUpgradeable(address(newGroupContract_))\n .transferOwnership(msg.sender);\n\n return address(newGroupContract_) ;\n }\n\n\n /**\n * @notice Adds principal tokens to a commitment group.\n * @param _newGroupContract The address of the group contract to add principal tokens to.\n * @param _initialPrincipalAmount The amount of principal tokens to add.\n * @param _principalTokenAddress The address of the principal token contract.\n */\n function _addPrincipalToCommitmentGroup(\n address _newGroupContract,\n uint256 _initialPrincipalAmount,\n address _principalTokenAddress\n ) internal returns (uint256) {\n\n\n IERC20(_principalTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _initialPrincipalAmount\n );\n IERC20(_principalTokenAddress).approve(\n _newGroupContract,\n _initialPrincipalAmount\n );\n\n address sharesRecipient = msg.sender; \n\n uint256 sharesAmount_ = ILenderCommitmentGroup(address(_newGroupContract))\n .addPrincipalToCommitmentGroup(\n _initialPrincipalAmount,\n sharesRecipient,\n 0 //_minShares\n );\n\n return sharesAmount_;\n }\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V2.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 \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V2 } from \"../../../interfaces/ILenderCommitmentGroup_V2.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingHelper} from \"../../../price_oracles/UniswapPricingHelper.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_Pool_V2 is\n ILenderCommitmentGroup_V2,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\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 address public immutable UNISWAP_PRICING_HELPER;\n \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 private firstDepositMade_deprecated; // no longer used\n uint256 public withdrawDelayTimeSeconds; // immutable for now - use withdrawDelayBypassForAccount\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 bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n \n mapping(address => bool) public withdrawDelayBypassForAccount;\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory,\n address _uniswapPricingHelper \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n UNISWAP_PRICING_HELPER = _uniswapPricingHelper; \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\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n \n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = 300;\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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \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, \"PRL\");\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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 = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Retrieves the price ratio from Uniswap for the given pool routes\n * @dev Calls the UniswapPricingLibrary to get TWAP (Time-Weighted Average Price) for the specified routes\n * @dev This is a low-level internal function that handles direct Uniswap oracle interaction\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The Uniswap price ratio expanded by the Uniswap expansion factor (2^96)\n */\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) internal view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n /**\n * @notice Calculates the principal token amount per collateral token based on Uniswap oracle prices\n * @dev Uses Uniswap TWAP and applies any configured maximum limits\n * @dev Returns the lesser of the oracle price or the configured maximum (if set)\n * @param poolOracleRoutes Array of pool route configurations to use for price calculation\n * @return The principal per collateral ratio, expanded by the Uniswap expansion factor\n */\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = IUniswapPricingLibrary(UNISWAP_PRICING_HELPER)\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 /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmount The exchange rate between principal and collateral (expanded by STANDARD_EXPANSION_FACTOR)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) internal 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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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\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\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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Allows accounts such as Yearn Vaults to bypass withdraw delay. \n * @dev This should ONLY be enabled for smart contracts that separately implement MEV/spam protection.\n * @param _addr The account that will have the bypass.\n * @param _bypass Whether or not bypass is enabled\n */\n function setWithdrawDelayBypassForAccount(address _addr, bool _bypass ) \n external \n onlyProtocolOwner {\n \n withdrawDelayBypassForAccount[_addr] = _bypass;\n \n }\n \n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n bool poolWasActivated = poolIsActivated();\n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n // if IS FIRST DEPOSIT then ONLY THE OWNER CAN DEPOSIT \n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n\n function poolIsActivated() public view virtual returns (bool){\n return totalSupply() >= 1e6; \n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n bool poolWasActivated = poolIsActivated();\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!poolWasActivated){\n require(msg.sender == owner(), \"FD\");\n require(poolIsActivated(), \"IS\"); \n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n\n\n require( \n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\"\n );\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(\n withdrawDelayBypassForAccount[msg.sender] || \n block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\"\n );\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!poolIsActivated() && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if ( !withdrawDelayBypassForAccount[msg.sender] && block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\n\n} " + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Pool_V3.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 import \"../../../interfaces/IPriceAdapter.sol\";\n\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\n \n\nimport \"../../../libraries/uniswap/TickMath.sol\"; \nimport \"../../../libraries/uniswap/FullMath.sol\";\n \n\nimport { LenderCommitmentGroupSharesIntegrated } from \"./LenderCommitmentGroupSharesIntegrated.sol\";\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\n\nimport { IERC4626 } from \"../../../interfaces/IERC4626.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_V3 } from \"../../../interfaces/ILenderCommitmentGroup_V3.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\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_Pool_V3 is\n ILenderCommitmentGroup_V3,\n IERC4626, // interface functions for lenders \n ISmartCommitment, // interface functions for borrowers (teller protocol) \n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable, \n ReentrancyGuardUpgradeable,\n LenderCommitmentGroupSharesIntegrated\n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\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 priceAdapter;\n \n \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 bytes32 public priceRouteHash;\n \n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; // DEPRECATED FOR NOW \n\n\n uint256 public lastUnpausedAt;\n bool public paused;\n bool public borrowingPaused;\n bool public liquidationAuctionPaused;\n\n\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 );\n \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 \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 \"OSCF\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"OTV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"OO\"\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 \"OP\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"BNA\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"SCF_P\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder \n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n\n \n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _priceAdapterRoute Route configuration for the principal/collateral oracle.\n\n */\n function initialize(\n\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n\n address _priceAdapter, \n \n bytes calldata _priceAdapterRoute\n\n \n ) external initializer {\n \n __Ownable_init();\n \n __Shares_init(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress\n ); //initialize the integrated shares \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, \"IRLB\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"ILTP\"); \n\n \n priceAdapter = _priceAdapter ;\n \n //internally this does checks and might revert \n // we register the price route with the adapter and save it locally \n priceRouteHash = IPriceAdapter( priceAdapter ).registerPriceRoute(\n _priceAdapterRoute\n );\n\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 );\n }\n\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 whenBorrowingNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"MMCT\"\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), \"IIR\");\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, \"LMD\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"C\"\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\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 * @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 function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenLiquidationAuctionNotPaused 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 \"TAD\"\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 * @notice Returns the timestamp when the contract was last unpaused\n * @dev Compares the internal lastUnpausedAt timestamp with the timestamp from the SmartCommitmentForwarder\n * @dev This accounts for pauses from both this contract and the forwarder\n * @return The maximum timestamp between the contract's last unpause and the forwarder's last unpause\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 /**\n * @notice Sets the lastUnpausedAt timestamp to the current block timestamp\n * @dev Called internally when the contract is unpaused\n * @dev This timestamp is used to calculate valid liquidation windows after unpausing\n */\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n /**\n * @notice Gets the total principal amount of a loan\n * @dev Retrieves loan details from the TellerV2 contract\n * @param _bidId The unique identifier of the loan bid\n * @return principalAmount The total principal amount of the loan\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 /**\n * @notice Calculates the amount currently owed for a specific bid\n * @dev Calls the TellerV2 contract to calculate the principal and interest due\n * @dev Uses the current block.timestamp to calculate up-to-date amounts\n * @param _bidId The unique identifier of the loan bid\n * @return principal The principal amount currently owed\n * @return interest The interest amount currently owed\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 /**\n * @notice Returns the cumulative token difference from all liquidations\n * @dev This represents the net gain or loss of principal tokens from liquidation events\n * @dev Positive values indicate the pool has gained tokens from liquidations\n * @dev Negative values indicate the pool has given out tokens as liquidation incentives\n * @return The current token difference from all liquidations as a signed integer\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 \n require(\n _loanDefaultedTimestamp > 0 && block.timestamp > _loanDefaultedTimestamp,\n \"LDT\"\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 /**\n * @notice Calculates the absolute value of an integer\n * @dev Utility function to convert a signed integer to its unsigned absolute value\n * @param x The signed integer input\n * @return The absolute value of x as an unsigned integer\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\n \n // principalPerCollateralAmount\n uint256 priceRatioQ96 = IPriceAdapter( priceAdapter )\n .getPriceRatioQ96(priceRouteHash);\n \n \n \n\n return\n getRequiredCollateral(\n principalAmount,\n priceRatioQ96 // principalPerCollateralAmount \n );\n }\n\n \n \n\n /**\n * @notice Calculates the amount of collateral tokens required for a given principal amount\n * @dev Converts principal amount to equivalent collateral based on current price ratio\n * @dev Uses the Math.mulDiv function with rounding up to ensure sufficient collateral\n * @param _principalAmount The amount of principal tokens to be borrowed\n * @param _maxPrincipalPerCollateralAmountQ96 The exchange rate between principal and collateral (expanded by Q96)\n * @return The required amount of collateral tokens, rounded up to ensure sufficient collateralization\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmountQ96 //price ratio Q96 \n \n ) internal view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n Q96,\n _maxPrincipalPerCollateralAmountQ96,\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\n\n /**\n * @notice 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 * @param _amount Amount of tokens to withdraw\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 \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 (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 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 internal \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 Converts an amount to its underlying value using a given exchange rate with rounding down\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding down to prevent favorable rounding for users\n * @dev This function is used for conversions where rounding down protects the protocol (e.g., calculating shares to mint)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded down\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 value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Down // Explicitly round down\n );\n\n\n }\n\n\n /**\n * @notice Converts an amount to its underlying value using a given exchange rate with rounding up\n * @dev Uses MathUpgradeable.mulDiv with explicit rounding up to ensure protocol safety\n * @dev This function is used for conversions where rounding up protects the protocol (e.g., calculating assets needed for shares)\n * @param amount The amount to convert (in the source unit)\n * @param rate The exchange rate to apply, expanded by EXCHANGE_RATE_EXPANSION_FACTOR\n * @return value_ The converted value in the target unit, rounded up\n */\n function _valueOfUnderlyingRoundUpwards(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n \n value_ = MathUpgradeable.mulDiv(\n amount, \n EXCHANGE_RATE_EXPANSION_FACTOR, \n rate,\n MathUpgradeable.Rounding.Up // Explicitly round down\n ); \n\n }\n\n\n\n\n /**\n * @notice Calculates the total amount of principal tokens currently lent out in active loans\n * @dev Subtracts the total repaid principal from the total lent principal\n * @dev Returns 0 if repayments exceed lending (which should not happen in normal operation)\n * @return The net amount of principal tokens currently outstanding in active loans\n */\n function getTotalPrincipalTokensOutstandingInActiveLoans()\n internal \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 * @notice Returns the address of the collateral token accepted by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This is used by the SmartCommitmentForwarder to verify collateral compatibility\n * @return The address of the ERC20 token used as collateral in this pool\n */\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n } \n \n\n /**\n * @notice Returns the type of collateral token supported by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This pool only supports ERC20 tokens as collateral\n * @return The collateral token type (ERC20) from the CommitmentCollateralType enum\n */\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n /**\n * @notice Returns the Teller V2 market ID associated with this lending pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The market ID is set during contract initialization and cannot be changed\n * @return The unique market ID within the Teller V2 protocol\n */\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n /**\n * @notice Returns the maximum allowed duration for loans in this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev This value is set during contract initialization and represents seconds\n * @dev Borrowers cannot request loans with durations exceeding this value\n * @return The maximum loan duration in seconds\n */\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n /**\n * @notice Calculates the current utilization ratio of the pool\n * @dev The utilization ratio is the percentage of committed funds currently out on loans\n * @dev Formula: (outstandingLoans + activeLoansAmountDelta) / poolTotalEstimatedValue * 10000\n * @dev Result is capped at 10000 (100%)\n * @param activeLoansAmountDelta Additional loan amount to consider for utilization calculation\n * @return The utilization ratio as a percentage with 2 decimal precision (e.g., 7500 = 75.00%)\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 * @notice Calculates the minimum interest rate based on current pool utilization\n * @dev The interest rate scales linearly between lower and upper bounds based on utilization\n * @dev Formula: lowerBound + (upperBound - lowerBound) * utilizationRatio\n * @dev Higher utilization results in higher interest rates to incentivize repayments\n * @param amountDelta Additional amount to consider when calculating utilization for this rate\n * @return The minimum interest rate as a percentage with 2 decimal precision (e.g., 500 = 5.00%)\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 /**\n * @notice Returns the address of the principal token used by this pool\n * @dev Implements the ISmartCommitment interface requirement\n * @dev The principal token is the asset that lenders deposit and borrowers borrow\n * @return The address of the ERC20 token used as principal in this pool\n */\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n /**\n * @notice Calculates the amount of principal tokens available for new loans\n * @dev The available amount is limited by the liquidity threshold percentage of the pool\n * @dev Formula: min(poolValueThreshold - outstandingLoans, 0)\n * @dev The pool won't allow borrowing beyond the configured threshold to maintain liquidity for withdrawals\n * @return The amount of principal tokens available for new loans, returns 0 if threshold is reached\n */\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n\n // Calculate the threshold value once to avoid duplicate calculations\n uint256 poolValueThreshold = uint256(getPoolTotalEstimatedValue()).percent(liquidityThresholdPercent);\n \n // Get the outstanding loan amount\n uint256 outstandingLoans = getTotalPrincipalTokensOutstandingInActiveLoans();\n \n // If outstanding loans exceed or equal the threshold, return 0\n if (poolValueThreshold <= outstandingLoans) {\n return 0;\n }\n \n // Return the difference between threshold and outstanding loans\n return poolValueThreshold - outstandingLoans;\n\n \n \n }\n\n\n\n /**\n * @notice Sets the delay time for withdrawing shares. 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 , \"WD\");\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n\n // ------------------------ Pausing functions ------------ \n\n\n\n event Paused(address account);\n event Unpaused(address account);\n\n event PausedBorrowing(address account);\n event UnpausedBorrowing(address account);\n\n event PausedLiquidationAuction(address account);\n event UnpausedLiquidationAuction(address account);\n\n\n modifier whenPaused() {\n require(paused, \"P\");\n _;\n }\n modifier whenNotPaused() {\n require(!paused, \"P\");\n _;\n }\n\n modifier whenBorrowingPaused() {\n require(borrowingPaused, \"P\");\n _;\n }\n modifier whenBorrowingNotPaused() {\n require(!borrowingPaused, \"P\");\n _;\n }\n\n modifier whenLiquidationAuctionPaused() {\n require(liquidationAuctionPaused, \"P\");\n _;\n }\n modifier whenLiquidationAuctionNotPaused() {\n require(!liquidationAuctionPaused, \"P\");\n _;\n }\n\n\n\n function _pause() internal {\n paused = true;\n emit Paused(_msgSender());\n }\n\n function _unpause() internal {\n paused = false;\n emit Unpaused(_msgSender());\n }\n\n\n function _pauseBorrowing() internal {\n borrowingPaused = true;\n emit PausedBorrowing(_msgSender());\n }\n\n function _unpauseBorrowing() internal {\n borrowingPaused = false;\n emit UnpausedBorrowing(_msgSender());\n }\n\n\n function _pauseLiquidationAuction() internal {\n liquidationAuctionPaused = true;\n emit PausedLiquidationAuction(_msgSender());\n }\n\n function _unpauseLiquidationAuction() internal {\n liquidationAuctionPaused = false;\n emit UnpausedLiquidationAuction(_msgSender());\n }\n\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol pause borrowing\n */\n function pauseBorrowing() public virtual onlyProtocolPauser whenBorrowingNotPaused {\n _pauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause borrowing\n */\n function unpauseBorrowing() public virtual onlyProtocolPauser whenBorrowingPaused {\n //setLastUnpausedAt(); // dont need this, can still liq when borrowing is paused \n _unpauseBorrowing();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol pause liquidation auctions\n */\n function pauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionNotPaused {\n _pauseLiquidationAuction();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol unpause liquidation auctions\n */\n function unpauseLiquidationAuction() public virtual onlyProtocolPauser whenLiquidationAuctionPaused {\n setLastUnpausedAt(); \n _unpauseLiquidationAuction();\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pausePool() 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 unpausePool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n\n\n // ------------------------ ERC4626 functions ------------ \n\n\n\n \n\n\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n \n function deposit(uint256 assets, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n\n // Similar to addPrincipalToCommitmentGroup but following ERC4626 standard\n require(assets > 0 );\n \n \n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n\n\n // Calculate shares after transfer\n shares = _valueOfUnderlying(assets, sharesExchangeRate());\n\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"FDM\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n // emit LenderAddedPrincipal(msg.sender, assets, shares, receiver);\n emit Deposit( msg.sender,receiver, assets, shares );\n\n return shares;\n }\n\n \n function mint(uint256 shares, address receiver) \n public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Calculate assets needed for desired shares\n assets = previewMint(shares);\n require(assets > 0);\n\n\n \n // Transfer assets from sender to vault\n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n principalToken.safeTransferFrom(msg.sender, address(this), assets);\n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n require(principalTokenBalanceAfter == principalTokenBalanceBefore + assets, \"TB\");\n \n // Update totals\n totalPrincipalTokensCommitted += assets;\n \n // Mint shares to receiver\n mintShares(receiver, shares);\n \n // Check first deposit conditions\n if(!firstDepositMade){\n require(msg.sender == owner(), \"IC\");\n require(shares >= 1e6, \"IS\");\n firstDepositMade = true;\n }\n \n \n emit Deposit( msg.sender,receiver, assets, shares );\n return assets;\n }\n\n \n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 shares) {\n \n // Calculate shares required for desired assets\n shares = previewWithdraw(assets);\n require(shares > 0);\n \n \n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SW\");\n\n require(msg.sender == owner, \"UA\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return shares;\n } \n\n \n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public \n whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n virtual \n returns (uint256 assets) {\n\n // Similar to burnSharesToWithdrawEarnings but following ERC4626 standard\n require(shares > 0);\n \n // Calculate assets to receive\n assets = _valueOfUnderlying(shares, sharesExchangeRateInverse());\n \n require(msg.sender == owner, \"UA\");\n\n // Check withdrawal delay\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n require(block.timestamp >= sharesLastTransferredAt + withdrawDelayTimeSeconds, \"SR\");\n \n // Burn shares from owner\n burnShares(owner, shares);\n \n // Update totals\n totalPrincipalTokensWithdrawn += assets;\n \n // Transfer assets to receiver\n principalToken.safeTransfer(receiver, assets);\n \n emit Withdraw(\n owner,\n receiver,\n owner,\n assets,\n shares\n );\n\n return assets;\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256) {\n return getPoolTotalEstimatedValue();\n }\n\n \n \n \n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _valueOfUnderlying(assets, sharesExchangeRate());\n } \n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _valueOfUnderlying(shares, sharesExchangeRateInverse());\n }\n\n \n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(assets, sharesExchangeRate());\n }\n\n \n function previewMint(uint256 shares) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards(shares, sharesExchangeRateInverse());\n \n \n }\n\n \n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n \n \n return _valueOfUnderlyingRoundUpwards( assets, sharesExchangeRate() ) ;\n \n }\n\n \n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n \n return _valueOfUnderlying(shares, sharesExchangeRateInverse()); \n \n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n\n\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n\n if(!firstDepositMade && msg.sender != owner()){\n return 0;\n }\n \n return type(uint256).max;\n }\n\n \n function maxWithdraw(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 ownerAssets = convertToAssets(balanceOf(owner));\n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n \n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n return Math.min(ownerAssets, availableLiquidity);\n }\n\n \n function maxRedeem(address owner) public view virtual returns (uint256) {\n if (paused) {\n return 0;\n }\n \n uint256 availableShares = balanceOf(owner);\n uint256 sharesLastTransferredAt = getSharesLastTransferredAt(owner);\n \n if (block.timestamp <= sharesLastTransferredAt + withdrawDelayTimeSeconds) {\n return 0;\n }\n \n uint256 availableLiquidity = principalToken.balanceOf(address(this));\n uint256 maxSharesBasedOnLiquidity = convertToShares(availableLiquidity);\n \n return Math.min(availableShares, maxSharesBasedOnLiquidity);\n }\n\n \n function asset() public view returns (address assetTokenAddress) {\n\n return address(principalToken) ; \n }\n\n\n\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 bool public liquidationsPaused; \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 \"oSCF\"\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, \"IRL\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"LTP\"); \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, \"PRL\");\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 \"ST\"\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, \"B\" );\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, \"SM\" );\n \n if(!firstDepositMade){\n require(msg.sender == owner(), \"F.\");\n require( sharesAmount_>= 1e6, \"SA\" );\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 \"CT\"\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 \"LMP\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"BC\"\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 ,\"W\");\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 require(!liquidationsPaused );\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 );\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() external 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 \"Ldt\"\n );\n require(\n block.timestamp > _loanDefaultedTimestamp,\n \"Ldp\"\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\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pauseLiquidations() public virtual onlyProtocolPauser {\n require(!liquidationsPaused);\n liquidationsPaused = true;\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop.\n */\n function unpauseLiquidations() public virtual onlyProtocolPauser {\n\n require(liquidationsPaused);\n\n setLastUnpausedAt();\n liquidationsPaused = false;\n }\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/LenderCommitmentGroup/LenderCommitmentGroupSharesIntegrated.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n \nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\n// import \"../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol\";\n\n /*\n\n This ERC20 token keeps track of the last time it was transferred and provides that information\n\n This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose \n \n Ideally , deploy this as a beacon proxy that is upgradeable \n\n */\n\nabstract contract LenderCommitmentGroupSharesIntegrated is\n Initializable, \n ERC20Upgradeable \n // ILenderCommitmentGroupSharesIntegrated\n{\n \n uint8 private constant DECIMALS = 18;\n \n mapping(address => uint256) private poolSharesLastTransferredAt;\n\n event SharesLastTransferredAt(\n address indexed recipient, \n uint256 transferredAt \n );\n\n \n\n /*\n The two tokens MUST implement IERC20Metadata or else this will fail.\n\n */\n function __Shares_init(\n address principalTokenAddress,\n address collateralTokenAddress\n ) internal onlyInitializing {\n\n string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol();\n string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol();\n \n // Create combined name and symbol\n string memory combinedName = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol, \" shares\"\n ));\n string memory combinedSymbol = string(abi.encodePacked(\n principalTokenSymbol, \"-\", collateralTokenSymbol\n ));\n \n // Initialize with the dynamic name and symbol\n __ERC20_init(combinedName, combinedSymbol); \n\n }\n \n\n function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call \n _mint(_recipient, _amount); //triggers _afterTokenTransfer\n\n\n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_recipient);\n } \n }\n\n function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call \n _burn(_burner, _amount); //triggers _afterTokenTransfer\n\n \n if (_amount > 0) {\n _setPoolSharesLastTransferredAt(_burner);\n } \n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n \n\n // this occurs after mint, burn and transfer \n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n _setPoolSharesLastTransferredAt(from);\n } \n \n }\n\n\n function _setPoolSharesLastTransferredAt( address from ) internal {\n\n poolSharesLastTransferredAt[from] = block.timestamp;\n emit SharesLastTransferredAt(from, block.timestamp); \n\n }\n\n /*\n Get the last timestamp pool shares have been transferred for this account \n */\n function getSharesLastTransferredAt(\n address owner \n ) public view returns (uint256) {\n\n return poolSharesLastTransferredAt[owner];\n \n }\n\n\n // Storage gap for future upgrades\n uint256[50] private __gap;\n \n\n\n}\n\n\n\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/BorrowSwap_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/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n */\n\n\ncontract BorrowSwap_G1 is PeripheryPayments, IUniswapV3SwapCallback {\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 BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n\n address token0,\n address token1,\n int256 amount0,\n int256 amount1 \n \n );\n\n \n // we take out a new loan with these args \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 SwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n uint160 sqrtPriceLimitX96; // optional, protects again sandwich atk\n\n\n // uint256 flashAmount;\n // bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n // 2. Add a struct for the callback data\n struct SwapCallbackData {\n address token0;\n address token1;\n uint24 fee;\n }\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 function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n\n\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n\n \n //lock up our collateral , get principal \n // Accept commitment and receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n\n\n bool zeroForOne = _swapArgs.token0 == _principalToken ;\n\n\n \n // swap principal For Collateral \n // do a single sided swap using uniswap - swap the principal we just got for collateral \n\n ( int256 amount0, int256 amount1 ) = IUniswapV3Pool( \n getUniswapPoolAddress (\n _swapArgs.token0,\n _swapArgs.token1,\n _swapArgs.fee\n )\n ).swap( \n address(this), \n zeroForOne,\n\n int256( _additionalInputAmount + acceptCommitmentAmount ) ,\n _swapArgs.sqrtPriceLimitX96, \n abi.encode(\n SwapCallbackData({\n token0: _swapArgs.token0,\n token1: _swapArgs.token1,\n fee: _swapArgs.fee\n })\n ) \n\n ); \n\n\n\n // Transfer tokens to the borrower if amounts are negative\n // In Uniswap, negative amounts mean the pool sends those tokens to the specified recipient\n if (amount0 < 0) {\n // Use uint256(-amount0) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token0, borrower, uint256(-amount0));\n }\n if (amount1 < 0) {\n // Use uint256(-amount1) to get the absolute value\n TransferHelper.safeTransfer(_swapArgs.token1, borrower, uint256(-amount1));\n }\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _swapArgs.token0,\n _swapArgs.token1,\n amount0 ,\n amount1 \n );\n\n \n \n\n \n }\n\n\n\n /**\n * @notice Uniswap V3 callback for flash swaps\n * @dev The pool calls this function after executing a swap\n * @param amount0Delta The change in token0 balance that occurred during the swap\n * @param amount1Delta The change in token1 balance that occurred during the swap\n * @param data Extra data passed to the pool during the swap call\n */\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n\n SwapCallbackData memory _swapArgs = abi.decode(data, (SwapCallbackData));\n \n\n // Validate that the msg.sender is a valid pool\n address pool = getUniswapPoolAddress(\n _swapArgs.token0, \n _swapArgs.token1, \n _swapArgs.fee\n );\n require(msg.sender == pool, \"Invalid pool callback\");\n\n // Determine which token we need to pay to the pool\n // If amount0Delta > 0, we need to pay token0 to the pool\n // If amount1Delta > 0, we need to pay token1 to the pool\n if (amount0Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token0, msg.sender, uint256(amount0Delta));\n } else if (amount1Delta > 0) {\n TransferHelper.safeTransfer(_swapArgs.token1, msg.sender, uint256(amount1Delta));\n }\n\n\n \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 *\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 * @notice Calculates an appropriate sqrtPriceLimitX96 value for a swap based on current pool price\n * @dev Returns a price limit that is a certain percentage away from the current price\n * @param token0 The first token in the pair\n * @param token1 The second token in the pair\n * @param fee The fee tier of the pool\n * @param zeroForOne The direction of the swap (true = token0 to token1, false = token1 to token0)\n * @param bufferBps Buffer in basis points (1/10000) away from current price (e.g. 50 = 0.5%)\n * @return sqrtPriceLimitX96 The calculated price limit\n */\n function calculateSqrtPriceLimitX96(\n address token0,\n address token1,\n uint24 fee,\n bool zeroForOne,\n uint16 bufferBps\n ) public view returns (uint160 sqrtPriceLimitX96) {\n // Constants from Uniswap\n uint160 MIN_SQRT_RATIO = 4295128739;\n uint160 MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n \n // Get the pool address\n address poolAddress = getUniswapPoolAddress(token0, token1, fee);\n require(poolAddress != address(0), \"Pool does not exist\");\n \n // Get the current price from the pool\n (uint160 currentSqrtRatioX96,,,,,,) = IUniswapV3Pool(poolAddress).slot0();\n \n // Calculate price limit based on direction and buffer\n if (zeroForOne) {\n // When swapping from token0 to token1, price decreases\n // So we set a lower bound that's bufferBps% below current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Subtract buffer from current price, but ensure we don't go below MIN_SQRT_RATIO\n if (currentSqrtRatioX96 <= MIN_SQRT_RATIO + buffer) {\n return MIN_SQRT_RATIO + 1;\n } else {\n return currentSqrtRatioX96 - buffer;\n }\n } else {\n // When swapping from token1 to token0, price increases\n // So we set an upper bound that's bufferBps% above current price\n \n // Calculate the buffer amount (currentPrice * bufferBps / 10000)\n uint160 buffer = uint160((uint256(currentSqrtRatioX96) * bufferBps) / 10000);\n \n // Add buffer to current price, but ensure we don't go above MAX_SQRT_RATIO\n if (MAX_SQRT_RATIO - buffer <= currentSqrtRatioX96) {\n return MAX_SQRT_RATIO - 1;\n } else {\n return currentSqrtRatioX96 + buffer;\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/BorrowSwap_G2.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/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol';\n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G2 {\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 ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\n );\n\n\n \n // we take out a new loan with these args \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\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n // uint160 deadline; \n\n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n /**\n \n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap_G3.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/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\"; \n\n \nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\n \n \n \n \n\n /*\n\n A one-tx strategy to borrow funds and then immediately swap them using uniswap \n\n \n\n */\n\n\ncontract BorrowSwap_G3 {\n using AddressUpgradeable for address;\n \n \n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n ISwapRouter02 public immutable UNISWAP_SWAP_ROUTER; \n IQuoter public immutable UNISWAP_QUOTER; \n\n event BorrowSwapComplete(\n address borrower,\n uint256 loanId,\n address token0 ,\n\n uint256 amountIn,\n uint256 amountOut \n\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\n\n struct TokenSwapPath {\n uint24 poolFee ;\n address tokenOut ;\n }\n\n struct SwapArgs {\n\n TokenSwapPath[] swapPaths ; //used to build the bytes path \n \n uint160 amountOutMinimum; \n \n } \n\n\n \n\n /**\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _swapRouter The address of the UniswapV3 SwapRouter_02 \n * @param quoter The address of the UniswapV3 Quoter \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n \n address _swapRouter, //swapRouter02 \n\n address _quoter //quoter \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n UNISWAP_SWAP_ROUTER = ISwapRouter02( _swapRouter );\n UNISWAP_QUOTER = IQuoter( _quoter );\n }\n \n \n\n \n\n /**\n * @notice Borrows funds from a lender commitment and immediately swaps them through Uniswap V3.\n * @dev This function accepts a loan commitment, receives principal tokens, and swaps them \n * for another token using Uniswap V3. The swapped tokens are sent to the borrower.\n * Additional input tokens can be provided to increase the swap amount.\n * \n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract\n * @param _principalToken The address of the token being borrowed (input token for swap)\n * @param _additionalInputAmount Additional amount of principal token to add to the swap\n * @param _swapArgs Struct containing swap parameters including paths and minimum output\n * @param _acceptCommitmentArgs Struct containing loan commitment acceptance parameters\n * \n * @dev Emits BorrowSwapComplete event upon successful execution\n * @dev Requires borrower to have approved this contract for _additionalInputAmount if > 0\n */\n function borrowSwap(\n address _lenderCommitmentForwarder,\n \n address _principalToken ,\n uint256 _additionalInputAmount, //an additional amount \n \n SwapArgs calldata _swapArgs, \n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n \n address borrower = msg.sender ;\n \n \n if (_additionalInputAmount > 0) {\n TransferHelper.safeTransferFrom(_principalToken, borrower, address(this), _additionalInputAmount); \n }\n \n \n // Accept commitment, lock up collateral, receive funds to this contract -- the principal \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _lenderCommitmentForwarder,\n borrower,\n _principalToken, \n _acceptCommitmentArgs\n );\n \n\n uint256 totalInputAmount = acceptCommitmentAmount + _additionalInputAmount ;\n\n \n\n // Approve the router to spend DAI.\n TransferHelper.safeApprove( _principalToken , address(UNISWAP_SWAP_ROUTER), totalInputAmount);\n\n // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.\n // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.\n // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).\n ISwapRouter02.ExactInputParams memory swapParams =\n ISwapRouter02.ExactInputParams({\n path: generateSwapPath( _principalToken, _swapArgs.swapPaths ) ,//path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),\n recipient: address( borrower ) ,\n // deadline: _swapArgs.deadline,\n amountIn: totalInputAmount ,\n amountOutMinimum: _swapArgs.amountOutMinimum //can be 0 for testing -- get from IQuoter \n });\n\n // Executes the swap.\n uint256 swapAmountOut = UNISWAP_SWAP_ROUTER.exactInput( swapParams );\n\n\n emit BorrowSwapComplete(\n borrower, \n newLoanId,\n \n _principalToken ,\n totalInputAmount ,\n swapAmountOut \n );\n\n \n }\n\n\n\n \n /**\n * @notice Generates a Uniswap V3 swap path from input token and swap path array.\n * @dev Encodes token addresses and pool fees into bytes format required by Uniswap V3.\n * Supports single-hop (1 path) and double-hop (2 paths) swaps only.\n * \n * @param inputToken The address of the input token (starting token of the swap)\n * @param swapPaths Array of TokenSwapPath structs containing tokenOut and poolFee for each hop\n * \n * @return bytes The encoded swap path compatible with Uniswap V3 router\n * \n * @dev Reverts with \"invalid swap path length\" if swapPaths length is not 1 or 2\n * @dev For single hop: encodes (inputToken, poolFee, tokenOut)\n * @dev For double hop: encodes (inputToken, poolFee1, tokenOut1, poolFee2, tokenOut2)\n */\n function generateSwapPath(\n address inputToken, \n TokenSwapPath[] calldata swapPaths\n ) public view returns (bytes memory) {\n\n if (swapPaths.length == 1 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut ) ;\n }else if (swapPaths.length == 2 ){\n return abi.encodePacked(inputToken, swapPaths[0].poolFee, swapPaths[0].tokenOut, swapPaths[1].poolFee, swapPaths[1].tokenOut ) ;\n }else {\n\n revert(\"invalid swap path length\");\n }\n\n }\n \n\n\n /**\n * @notice Quotes the expected output amount for an exact input swap through Uniswap V3.\n * @dev Uses Uniswap V3 Quoter to simulate a swap and return expected output without executing.\n * This is a view function that doesn't modify state or execute any swaps.\n * \n * @param inputToken The address of the input token\n * @param amountIn The exact amount of input tokens to be swapped\n * @param swapPaths Array of TokenSwapPath structs defining the swap route\n * \n * @return amountOut The expected amount of output tokens from the swap\n * \n * @dev Uses generateSwapPath internally to create the swap path\n * @dev Returns only the amountOut from the quoter, ignoring other returned values\n */\n function quoteExactInput (\n\n address inputToken,\n uint256 amountIn,\n TokenSwapPath[] calldata swapPaths \n \n\n ) external view returns (uint256 amountOut) {\n\n (amountOut, , , ) = UNISWAP_QUOTER.quoteExactInput(\n generateSwapPath(inputToken,swapPaths),\n amountIn\n );\n\n }\n \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 \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/BorrowSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./BorrowSwap_G3.sol\";\n\ncontract BorrowSwap is BorrowSwap_G3 {\n constructor(\n address _tellerV2, \n address _swapRouter,\n address _quoter\n )\n BorrowSwap_G3(\n _tellerV2, \n _swapRouter,\n _quoter \n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/CommitmentRolloverLoan.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\";\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/ICommitmentRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\ncontract CommitmentRolloverLoan is ICommitmentRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _lenderCommitmentForwarder) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n }\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The ID of the existing loan.\n * @param _rolloverAmount The amount to rollover.\n * @param _commitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n function rolloverLoan(\n uint256 _loanId,\n uint256 _rolloverAmount,\n AcceptCommitmentArgs calldata _commitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n IERC20Upgradeable lendingToken = IERC20Upgradeable(\n TELLER_V2.getLoanLendingToken(_loanId)\n );\n uint256 balanceBefore = lendingToken.balanceOf(address(this));\n\n if (_rolloverAmount > 0) {\n //accept funds from the borrower to this contract\n lendingToken.transferFrom(borrower, address(this), _rolloverAmount);\n }\n\n // Accept commitment and receive funds to this contract\n newLoanId_ = _acceptCommitment(_commitmentArgs);\n\n // Calculate funds received\n uint256 fundsReceived = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n // Approve TellerV2 to spend funds and repay loan\n lendingToken.approve(address(TELLER_V2), fundsReceived);\n TELLER_V2.repayLoanFull(_loanId);\n\n uint256 fundsRemaining = lendingToken.balanceOf(address(this)) -\n balanceBefore;\n\n if (fundsRemaining > 0) {\n lendingToken.transfer(borrower, fundsRemaining);\n }\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n * @return _amount The calculated amount, positive if borrower needs to send funds and negative if they will receive funds.\n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _timestamp\n ) external view returns (int256 _amount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n _amount +=\n int256(repayAmountOwed.principal) +\n int256(repayAmountOwed.interest);\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 amountToBorrower = commitmentPrincipalRequested -\n amountToProtocol -\n amountToMarketplace;\n\n _amount -= int256(amountToBorrower);\n }\n\n /**\n * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(AcceptCommitmentArgs calldata _commitmentArgs)\n internal\n returns (uint256 bidId_)\n {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 msg.sender\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n//https://docs.aave.com/developers/v/1.0/tutorials/performing-a-flash-loan/...-in-your-project\n\ncontract FlashRolloverLoan_G1 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\n );\n\n _;\n }\n\n /*\n need to pass loanId and borrower \n */\n\n /**\n * @notice Allows a borrower to rollover a loan to a new commitment.\n * @param _loanId The bid id for the loan to repay\n * @param _flashLoanAmount The amount to flash borrow.\n * @param _acceptCommitmentArgs Arguments for the commitment to accept.\n * @return newLoanId_ The ID of the new loan created by accepting the commitment.\n */\n\n /*\n \nThe flash loan amount can naively be the exact amount needed to repay the old loan \n\nIf the new loan pays out (after fees) MORE than the aave loan amount+ fee) then borrower amount can be zero \n\n 1) I could solve for what the new loans payout (before fees and after fees) would NEED to be to make borrower amount 0...\n\n*/\n\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /*\n Notice: If collateral is being rolled over, it needs to be pre-approved from the borrower to the collateral manager \n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\n }\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 * @notice Internally accepts a commitment via the `LENDER_COMMITMENT_FORWARDER`.\n * @param _commitmentArgs Arguments required to accept a commitment.\n * @return bidId_ The ID of the bid associated with the accepted commitment.\n */\n function _acceptCommitment(\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 bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G2.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\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n// Interfaces\nimport \"./FlashRolloverLoan_G1.sol\";\n\ncontract FlashRolloverLoan_G2 is FlashRolloverLoan_G1 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G1(\n _tellerV2,\n _lenderCommitmentForwarder,\n _poolAddressesProvider\n )\n {}\n\n /*\n\n This assumes that the flash amount will be the repayLoanFull amount !!\n\n */\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G3.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/IFlashRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G3 is IFlashLoanSimpleReceiver, IFlashRolloverLoan {\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 ILenderCommitmentForwarder public immutable LENDER_COMMITMENT_FORWARDER;\n\n address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _lenderCommitmentForwarder,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n LENDER_COMMITMENT_FORWARDER = ILenderCommitmentForwarder(\n _lenderCommitmentForwarder\n );\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(LENDER_COMMITMENT_FORWARDER)\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(LENDER_COMMITMENT_FORWARDER)\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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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(uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return LENDER_COMMITMENT_FORWARDER.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 * @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/extensions/rollover/FlashRolloverLoan_G4.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/IFlashRolloverLoan_G4.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\ncontract FlashRolloverLoan_G4 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 * @return newLoanId_ Identifier of the new loan post rollover.\n */\n function rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external returns (uint256 newLoanId_) {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 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 uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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}\n \n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoan_G5.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/IFlashRolloverLoan_G4.sol\"; \nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n/*\nAdds smart commitment args \n*/\ncontract FlashRolloverLoan_G5 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G4 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee);\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 * @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/extensions/rollover/FlashRolloverLoan_G6.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n\n/*\n G6: Additionally incorporates referral rewards \n*/\n\n\ncontract FlashRolloverLoan_G6 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\n }\n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n * @param _loanId The ID of the loan to calculate the rollover amount for.\n * @param _commitmentArgs Arguments for the commitment.\n * @param _timestamp The timestamp for when the calculation is executed.\n \n */\n function calculateRolloverAmount(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n AcceptCommitmentArgs calldata _commitmentArgs,\n uint256 _rewardAmount, \n uint16 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 _marketId = _getMarketIdForCommitment(_lenderCommitmentForwarder,\n _commitmentArgs.commitmentId\n );\n uint16 marketFeePct = _getMarketFeePct(_marketId);\n uint16 protocolFeePct = _getProtocolFeePct();\n\n uint256 commitmentPrincipalRequested = _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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G7.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G7 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n IERC20(lendingToken).transferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan_G8.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\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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/IFlashRolloverLoan_G6.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n\nimport { IPool } from \"../../../interfaces/aave/IPool.sol\";\nimport { IFlashLoanSimpleReceiver } from \"../../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\nimport { IPoolAddressesProvider } from \"../../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n\n\n/*\n G7: Additionally adds calculations for SCF \n*/\n\n\ncontract FlashRolloverLoan_G8 is IFlashLoanSimpleReceiver, IFlashRolloverLoan_G6 {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n using SafeERC20 for ERC20;\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 address public immutable POOL_ADDRESSES_PROVIDER;\n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\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 *\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 _lenderCommitmentForwarder The address of the LenderCommitmentForwarder contract.\n * @param _poolAddressesProvider The address of the PoolAddressesProvider.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n POOL_ADDRESSES_PROVIDER = _poolAddressesProvider;\n }\n\n modifier onlyFlashLoanPool() {\n require(\n msg.sender == address(POOL()),\n \"FlashRolloverLoan: Must be called by FlashLoanPool\"\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 * @param _flashLoanAmount Amount of flash loan to be borrowed for the rollover.\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 rolloverLoanWithFlash(\n address _lenderCommitmentForwarder,\n uint256 _loanId,\n uint256 _flashLoanAmount,\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"CommitmentRolloverLoan: not borrower\");\n\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( _rewardAmount <= _flashLoanAmount/ 10, \"Reward amount may only be up to 1/10 of flash loan amount\" );\n\n if (_borrowerAmount > 0) {\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n _borrowerAmount\n );\n }\n\n // Call 'Flash' on the vault to borrow funds and call tellerV2FlashCallback\n // This ultimately calls executeOperation\n IPool(POOL()).flashLoanSimple(\n address(this),\n lendingToken,\n _flashLoanAmount,\n abi.encode(\n RolloverCallbackArgs({\n lenderCommitmentForwarder :_lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount,\n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs)\n })\n ),\n 0 //referral code\n );\n }\n\n /**\n *\n * @notice Callback function that is triggered by Aave during the flash loan process.\n * This function handles the logic to use the borrowed funds to rollover the loan,\n * make necessary repayments, and manage the loan commitments.\n *\n * @dev The function ensures the initiator is this contract, decodes the data provided by\n * the flash loan call, repays the original loan in full, accepts new loan commitments,\n * approves the repayment for the flash loan and then handles any remaining funds.\n * This function should only be called by the FlashLoanPool as ensured by the `onlyFlashLoanPool` modifier.\n *\n * @param _flashToken The token in which the flash loan is borrowed.\n * @param _flashAmount The amount of tokens borrowed via the flash loan.\n * @param _flashFees The fees associated with the flash loan to be repaid to Aave.\n * @param _initiator The address initiating the flash loan (must be this contract).\n * @param _data Encoded data containing necessary information for loan rollover.\n *\n * @return Returns true if the operation was successful.\n */\n function executeOperation(\n address _flashToken,\n uint256 _flashAmount,\n uint256 _flashFees,\n address _initiator,\n bytes calldata _data\n ) external virtual onlyFlashLoanPool returns (bool) {\n require(\n _initiator == address(this),\n \"This contract must be the initiator\"\n );\n\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(\n _data,\n (RolloverCallbackArgs)\n );\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId,\n _flashToken,\n _flashAmount\n );\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n // Accept commitment and receive funds to this contract\n\n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n _flashToken,\n acceptCommitmentArgs\n );\n\n //approve the repayment for the flash loan\n IERC20Upgradeable(_flashToken).approve(\n address(POOL()),\n _flashAmount + _flashFees\n );\n\n uint256 fundsRemaining = acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n _flashFees;\n\n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){\n\n //make sure reward amount isnt TOO much here ? \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.rewardRecipient,\n _rolloverArgs.rewardAmount\n );\n\n }\n\n IERC20Upgradeable(_flashToken).transfer(\n _rolloverArgs.borrower,\n fundsRemaining\n );\n }\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n return true;\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 function ADDRESSES_PROVIDER() public view returns (IPoolAddressesProvider) {\n return IPoolAddressesProvider(POOL_ADDRESSES_PROVIDER);\n }\n\n function POOL() public view returns (IPool) {\n return IPool(ADDRESSES_PROVIDER().getPool());\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 _flashloanPremiumPct,\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\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(_flashloanPremiumPct);\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\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 * @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/extensions/rollover/FlashRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G5.sol\";\n\ncontract FlashRolloverLoan is FlashRolloverLoan_G5 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G5(\n _tellerV2,\n _poolAddressesProvider\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/FlashRolloverLoanWidget.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./FlashRolloverLoan_G8.sol\";\n\ncontract FlashRolloverLoanWidget is FlashRolloverLoan_G8 {\n constructor(\n address _tellerV2,\n address _poolAddressesProvider\n )\n FlashRolloverLoan_G8(\n _tellerV2,\n _poolAddressesProvider\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_G2.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_G2 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 \n _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \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 \n /*\n Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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_G2.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G2 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G2(\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_G2.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.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_G2 is\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\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 /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G2(_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 _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 //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 //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 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. 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 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" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./LenderCommitmentForwarder_G2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G3 is\n LenderCommitmentForwarder_G2,\n ExtensionsContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G2(_tellerV2, _marketRegistry)\n {}\n\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/LenderCommitmentForwarder_U1.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_U1.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\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\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_U1 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U1\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 => 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 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 //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 scaledPoolOraclePrice = getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n ).percent(commitmentPoolOracleLtvRatio[_commitmentId]);\n\n bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId]\n .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = usePoolRoutes\n ? Math.min(\n scaledPoolOraclePrice,\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 (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 (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 \n This returns a price ratio which to be normalized, must be divided by STANDARD_EXPANSION_FACTOR\n\n */\n\n function getUniswapPriceRatioForPoolRoutes(\n 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 PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/LenderCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\ncontract LenderCommitmentForwarder is LenderCommitmentForwarder_G1 {\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G1(_tellerV2, _marketRegistry)\n {\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U1.sol\";\n\ncontract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U1(\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/LenderCommitmentForwarderStaging.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G3.sol\";\n\ncontract LenderCommitmentForwarderStaging is\n ILenderCommitmentForwarder,\n LenderCommitmentForwarder_G3\n{\n constructor(address _tellerV2, address _marketRegistry)\n LenderCommitmentForwarder_G3(_tellerV2, _marketRegistry)\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 require(fundsRemaining >= _reward, \"Insufficient funds for reward\");\n\n if (_reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _rewardRecipient, _reward);\n }\n\n if (fundsRemaining - _reward > 0) {\n TransferHelper.safeTransfer(principalTokenAddress, _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 onlyOracleApprovedAllowEOA 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/LenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/ILenderManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/IMarketRegistry.sol\";\n\ncontract LenderManager is\n Initializable,\n OwnableUpgradeable,\n ERC721Upgradeable,\n ILenderManager\n{\n IMarketRegistry public immutable marketRegistry;\n\n constructor(IMarketRegistry _marketRegistry) {\n marketRegistry = _marketRegistry;\n }\n\n function initialize() external initializer {\n __LenderManager_init();\n }\n\n function __LenderManager_init() internal onlyInitializing {\n __Ownable_init();\n __ERC721_init(\"TellerLoan\", \"TLN\");\n }\n\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)\n public\n override\n onlyOwner\n {\n _safeMint(_newLender, _bidId, \"\");\n }\n\n /**\n * @notice Returns the address of the lender that owns a given loan/bid.\n * @param _bidId The id of the bid of which to return the market id\n */\n function _getLoanMarketId(uint256 _bidId) internal view returns (uint256) {\n return ITellerV2(owner()).getLoanMarketId(_bidId);\n }\n\n /**\n * @notice Returns the verification status of a lender for a market.\n * @param _lender The address of the lender which should be verified by the market\n * @param _bidId The id of the bid of which to return the market id\n */\n function _hasMarketVerification(address _lender, uint256 _bidId)\n internal\n view\n virtual\n returns (bool isVerified_)\n {\n uint256 _marketId = _getLoanMarketId(_bidId);\n\n (isVerified_, ) = marketRegistry.isVerifiedLender(_marketId, _lender);\n }\n\n /** ERC721 Functions **/\n\n function _beforeTokenTransfer(address, address to, uint256 tokenId, uint256)\n internal\n override\n {\n require(_hasMarketVerification(to, tokenId), \"Not approved by market\");\n }\n\n function _baseURI() internal view override returns (string memory) {\n return \"\";\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/erc4626/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\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 {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "contracts/libraries/erc4626/ERC4626.sol": { + "content": " // https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol\n\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n \n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "contracts/libraries/erc4626/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}" + }, + "contracts/libraries/erc4626/VaultTokenWrapper.sol": { + "content": " \n\n pragma solidity >=0.8.0;\n \n import \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport {ERC4626} from \"./ERC4626.sol\";\n\nimport {ERC20} from \"./ERC20.sol\";\nimport {SafeERC20} from \"../../openzeppelin/SafeERC20.sol\";\n \n import {FixedPointMathLib} from \"./utils/FixedPointMathLib.sol\";\n\ncontract TellerPoolVaultWrapper is ERC4626 {\n\n \n\n using SafeERC20 for IERC20;\n\n using FixedPointMathLib for uint256;\n\n \n address public immutable lenderPool;\n\n constructor(\n ERC20 _assetToken, //original pool shares -- underlying asset \n address _lenderPool, // the pool address \n string memory _name,\n string memory _symbol\n ) ERC4626(_assetToken, _name, _symbol ) {\n\n \n lenderPool = _lenderPool ; \n\n }\n\n\n\n\n function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )) .safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n IERC20( address( asset )).safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n IERC20( address( asset )).safeTransfer(receiver, assets);\n }\n\n\n\n // -----------\n\n\n\n function totalAssets() public view override returns (uint256) {\n\n\n }\n\n function convertToShares(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view override returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view override returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view override returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view override returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view override returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view override returns (uint256) {\n return balanceOf[owner];\n }\n\n\n\n}\n\n" + }, + "contracts/libraries/ExcessivelySafeCall.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.7.6;\n\nlibrary ExcessivelySafeCall {\n uint256 constant LOW_28_MASK =\n 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _value The value in wei to send to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeCall(\n address _target,\n uint256 _gas,\n uint256 _value,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := call(\n _gas, // gas\n _target, // recipient\n _value, // ether value\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /// @notice Use when you _really_ really _really_ don't trust the called\n /// contract. This prevents the called contract from causing reversion of\n /// the caller in as many ways as we can.\n /// @dev The main difference between this and a solidity low-level call is\n /// that we limit the number of bytes that the callee can cause to be\n /// copied to caller memory. This prevents stupid things like malicious\n /// contracts returning 10,000,000 bytes causing a local OOG when copying\n /// to memory.\n /// @param _target The address to call\n /// @param _gas The amount of gas to forward to the remote contract\n /// @param _maxCopy The maximum number of bytes of returndata to copy\n /// to memory.\n /// @param _calldata The data to send to the remote contract\n /// @return success and returndata, as `.call()`. Returndata is capped to\n /// `_maxCopy` bytes.\n function excessivelySafeStaticCall(\n address _target,\n uint256 _gas,\n uint16 _maxCopy,\n bytes memory _calldata\n ) internal view returns (bool, bytes memory) {\n // set up for assembly call\n uint256 _toCopy;\n bool _success;\n bytes memory _returnData = new bytes(_maxCopy);\n // dispatch message to recipient\n // by assembly calling \"handle\" function\n // we call via assembly to avoid memcopying a very large returndata\n // returned by a malicious contract\n assembly {\n _success := staticcall(\n _gas, // gas\n _target, // recipient\n add(_calldata, 0x20), // inloc\n mload(_calldata), // inlen\n 0, // outloc\n 0 // outlen\n )\n // limit our copy to 256 bytes\n _toCopy := returndatasize()\n if gt(_toCopy, _maxCopy) {\n _toCopy := _maxCopy\n }\n // Store the length of the copied bytes\n mstore(_returnData, _toCopy)\n // copy the bytes from returndata[0:_toCopy]\n returndatacopy(add(_returnData, 0x20), 0, _toCopy)\n }\n return (_success, _returnData);\n }\n\n /**\n * @notice Swaps function selectors in encoded contract calls\n * @dev Allows reuse of encoded calldata for functions with identical\n * argument types but different names. It simply swaps out the first 4 bytes\n * for the new selector. This function modifies memory in place, and should\n * only be used with caution.\n * @param _newSelector The new 4-byte selector\n * @param _buf The encoded contract args\n */\n function swapSelector(bytes4 _newSelector, bytes memory _buf)\n internal\n pure\n {\n require(_buf.length >= 4);\n uint256 _mask = LOW_28_MASK;\n assembly {\n // load the first word of\n let _word := mload(add(_buf, 0x20))\n // mask out the top 4 bytes\n // /x\n _word := and(_word, _mask)\n _word := or(_newSelector, _word)\n mstore(add(_buf, 0x20), _word)\n }\n }\n}" + }, + "contracts/libraries/FixedPointQ96.sol": { + "content": "\n\n\n\n//use mul div and make sure we round the proper way ! \n\n\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) \nlibrary FixedPointQ96 {\n uint8 constant RESOLUTION = 96;\n uint256 constant Q96 = 0x1000000000000000000000000;\n\n\n\n // Example: Convert a decimal number (like 0.5) into FixedPoint96 format\n function toFixedPoint96(uint256 numerator, uint256 denominator) public pure returns (uint256) {\n // The number is scaled by Q96 to convert into fixed point format\n return (numerator * Q96) / denominator;\n }\n\n // Example: Multiply two fixed-point numbers\n function multiplyFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Multiply the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * fixedPointB) / Q96;\n }\n\n // Example: Divide two fixed-point numbers\n function divideFixedPoint96(uint256 fixedPointA, uint256 fixedPointB) public pure returns (uint256) {\n // Divide the two fixed-point numbers and scale back by Q96 to maintain precision\n return (fixedPointA * Q96) / fixedPointB;\n }\n\n\n function fromFixedPoint96(uint256 q96Value) public pure returns (uint256) {\n // To convert from Q96 back to normal (human-readable) value, divide by Q96\n return q96Value / Q96;\n }\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/IERC20Minimal.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\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/BitMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\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/core/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\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/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}" + }, + "contracts/libraries/uniswap/periphery/base/BlockTimestamp.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\n/// @title Function for getting block timestamp\n/// @dev Base contract that is overridden for tests\nabstract contract BlockTimestamp {\n /// @dev Method that exists purely to be overridden for tests\n /// @return The current block timestamp\n function _blockTimestamp() internal view virtual returns (uint256) {\n return block.timestamp;\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/base/PeripheryValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport './BlockTimestamp.sol';\n\nabstract contract PeripheryValidation is BlockTimestamp {\n modifier checkDeadline(uint256 deadline) {\n require(_blockTimestamp() <= deadline, 'Transaction too old');\n _;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC1271.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for verifying contract-based account signatures\n/// @notice Interface that verifies provided signature for the data\n/// @dev Interface defined by EIP-1271\ninterface IERC1271 {\n /// @notice Returns whether the provided signature is valid for the provided data\n /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.\n /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).\n /// MUST allow external calls.\n /// @param hash Hash of the data to be signed\n /// @param signature Signature byte array associated with _data\n /// @return magicValue The bytes4 magic value 0x1626ba7e\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IERC20PermitAllowed.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Interface for permit\n/// @notice Interface used by DAI/CHAI for permit\ninterface IERC20PermitAllowed {\n /// @notice Approve the spender to spend some tokens via the holder signature\n /// @dev This is the permit interface used by DAI and CHAI\n /// @param holder The address of the token holder, the token owner\n /// @param spender The address of the token spender\n /// @param nonce The holder's nonce, increases at each call to permit\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\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/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title IERC20Metadata\n/// @title Interface for ERC20 Metadata\n/// @notice Extension to IERC20 that includes token metadata\ninterface IERC20Metadata is IERC20 {\n /// @return The name of the token\n function name() external view returns (string memory);\n\n /// @return The symbol of the token\n function symbol() external view returns (string memory);\n\n /// @return The number of decimal places the token has\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\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/IPeripheryPaymentsWithFee.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport './IPeripheryPayments.sol';\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPaymentsWithFee is IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between\n /// 0 (exclusive), and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between\n /// 0 (exclusive) and 1 (inclusive) going to feeRecipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n function sweepTokenWithFee(\n address token,\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) external payable;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IPoolInitializer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n \n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of number of initialized ticks loaded\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n address pool;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `quoteExactInputSingleWithPool`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// amountIn The desired input amount\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n view\n returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleWithPoolParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n address pool;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleWithPoolParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amount The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// pool The address of the pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// amountOut The desired output amount\n /// fee The fee of the token pool to consider for the pair\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks loaded\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n view\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n view\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n}" + }, + "contracts/libraries/uniswap/periphery/interfaces/IQuoterV2.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title QuoterV2 Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.\n/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IQuoterV2 {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountIn The desired input amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n external\n returns (\n uint256 amountOut,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n /// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path\n /// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n external\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n );\n\n struct QuoteExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint256 amount;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`\n /// tokenIn The token being swapped in\n /// tokenOut The token being swapped out\n /// fee The fee of the token pool to consider for the pair\n /// amountOut The desired output amount\n /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n /// @return sqrtPriceX96After The sqrt price of the pool after the swap\n /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed\n /// @return gasEstimate The estimate of the gas that the swap consumes\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n external\n returns (\n uint256 amountIn,\n uint160 sqrtPriceX96After,\n uint32 initializedTicksCrossed,\n uint256 gasEstimate\n );\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/ISelfPermit.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Self Permit\n/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route\ninterface ISelfPermit {\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermit(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend a given token from `msg.sender`\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this).\n /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit\n /// @param token The address of the token spent\n /// @param value The amount that can be spent of token\n /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitIfNecessary(\n address token,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowed(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n\n /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter\n /// @dev The `owner` is always msg.sender and the `spender` is always address(this)\n /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.\n /// @param token The address of the token spent\n /// @param nonce The current nonce of the owner\n /// @param expiry The timestamp at which the permit is no longer valid\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function selfPermitAllowedIfNecessary(\n address token,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\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/interfaces/ISwapRouter02.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 ISwapRouter02 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 \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 \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 \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/interfaces/ITickLens.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Tick Lens\n/// @notice Provides functions for fetching chunks of tick data for a pool\n/// @dev This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and\n/// then sending additional multicalls to fetch the tick data\ninterface ITickLens {\n struct PopulatedTick {\n int24 tick;\n int128 liquidityNet;\n uint128 liquidityGross;\n }\n\n /// @notice Get all the tick data for the populated ticks from a word of the tick bitmap of a pool\n /// @param pool The address of the pool for which to fetch populated tick data\n /// @param tickBitmapIndex The index of the word in the tick bitmap for which to parse the bitmap and\n /// fetch all the populated ticks\n /// @return populatedTicks An array of tick data for the given word in the tick bitmap\n function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)\n external\n view\n returns (PopulatedTick[] memory populatedTicks);\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/IV3Migrator.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IMulticall.sol';\nimport './ISelfPermit.sol';\nimport './IPoolInitializer.sol';\n\n/// @title V3 Migrator\n/// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools\ninterface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer {\n struct MigrateParams {\n address pair; // the Uniswap v2-compatible pair\n uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender)\n uint8 percentageToMigrate; // represented as a numerator over 100\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Min; // must be discounted by percentageToMigrate\n uint256 amount1Min; // must be discounted by percentageToMigrate\n address recipient;\n uint256 deadline;\n bool refundAsETH;\n }\n\n /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3\n /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of\n /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an\n /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range\n /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata\n function migrate(MigrateParams calldata params) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/BytesLib.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity ^0.8.0;\n\n\nlibrary BytesLib {\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, 'slice_overflow');\n require(_start + _length >= _start, 'slice_overflow');\n require(_bytes.length >= _start + _length, 'slice_outOfBounds');\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_start + 20 >= _start, 'toAddress_overflow');\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\n require(_start + 3 >= _start, 'toUint24_overflow');\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\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/ChainId.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Function for getting the current chain ID\nlibrary ChainId {\n /// @dev Gets the current chain ID\n /// @return chainId The current chain ID\n function get() internal view returns (uint256 chainId) {\n assembly {\n chainId := chainid()\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/HexStrings.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary HexStrings {\n bytes16 internal constant ALPHABET = '0123456789abcdef';\n\n /// @notice Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n /// @dev Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55\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] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n require(value == 0, 'Strings: hex length insufficient');\n return string(buffer);\n }\n\n function toHexStringNoPrefix(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length);\n for (uint256 i = buffer.length; i > 0; i--) {\n buffer[i - 1] = ALPHABET[value & 0xf];\n value >>= 4;\n }\n return string(buffer);\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport '../../FullMath.sol';\nimport '../../FixedPoint96.sol';\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n /// @notice Downcasts uint256 to uint128\n /// @param x The uint258 to be downcasted\n /// @return y The passed value, downcasted to uint128\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param amount0 The amount of token0 being sent in\n /// @param amount1 The amount of token1 being sent in\n /// @return liquidity The maximum amount of liquidity received\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) / sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount of token1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/OracleLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n \npragma solidity ^0.8.0;\n\n\nimport '../../FullMath.sol';\nimport '../../TickMath.sol';\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\n/// @title Oracle library\n/// @notice Provides functions to integrate with V3 pool oracle\nlibrary OracleLibrary {\n /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n /// @param pool Address of the pool that we want to observe\n /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means\n /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp\n /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp\n function consult(address pool, uint32 secondsAgo)\n internal\n view\n returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)\n {\n require(secondsAgo != 0, 'BP');\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = secondsAgo;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =\n IUniswapV3Pool(pool).observe(secondsAgos);\n\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta =\n secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;\n\n // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128\n uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;\n harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination\n /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination\n /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken\n function getQuoteAtTick(\n int24 tick,\n uint128 baseAmount,\n address baseToken,\n address quoteToken\n ) internal pure returns (uint256 quoteAmount) {\n uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);\n\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 = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);\n quoteAmount = baseToken < quoteToken\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n\n /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation\n /// @param pool Address of Uniswap V3 pool that we want to observe\n /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool\n function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n require(observationCardinality > 0, 'NI');\n\n (uint32 observationTimestamp, , , bool initialized) =\n IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);\n\n // The next index might not be initialized if the cardinality is in the process of increasing\n // In this case the oldest observation is always in index 0\n if (!initialized) {\n (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);\n }\n\n secondsAgo = uint32(block.timestamp) - observationTimestamp;\n }\n\n /// @notice Given a pool, it returns the tick value as of the start of the current block\n /// @param pool Address of Uniswap V3 pool\n /// @return The tick that the pool was in at the start of the current block\n function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {\n (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();\n\n // 2 observations are needed to reliably calculate the block starting tick\n require(observationCardinality > 1, 'NEO');\n\n // If the latest observation occurred in the past, then no tick-changing trades have happened in this block\n // therefore the tick in `slot0` is the same as at the beginning of the current block.\n // We don't need to check if this observation is initialized - it is guaranteed to be.\n (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) =\n IUniswapV3Pool(pool).observations(observationIndex);\n if (observationTimestamp != uint32(block.timestamp)) {\n return (tick, IUniswapV3Pool(pool).liquidity());\n }\n\n uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;\n (\n uint32 prevObservationTimestamp,\n int56 prevTickCumulative,\n uint160 prevSecondsPerLiquidityCumulativeX128,\n bool prevInitialized\n ) = IUniswapV3Pool(pool).observations(prevIndex);\n\n require(prevInitialized, 'ONI');\n\n uint32 delta = observationTimestamp - prevObservationTimestamp;\n tick = int24((tickCumulative - prevTickCumulative) / int56(uint56(delta)));\n uint128 liquidity =\n uint128(\n (uint192(delta) * type(uint160).max) /\n (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)\n );\n return (tick, liquidity);\n }\n\n /// @notice Information for calculating a weighted arithmetic mean tick\n struct WeightedTickData {\n int24 tick;\n uint128 weight;\n }\n\n /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick\n /// @param weightedTickData An array of ticks and weights\n /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick\n /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,\n /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).\n /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.\n function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)\n internal\n pure\n returns (int24 weightedArithmeticMeanTick)\n {\n // Accumulates the sum of products between each tick and its weight\n int256 numerator;\n\n // Accumulates the sum of the weights\n uint256 denominator;\n\n // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic\n for (uint256 i; i < weightedTickData.length; i++) {\n numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));\n denominator += weightedTickData[i].weight;\n }\n\n weightedArithmeticMeanTick = int24(numerator / int256(denominator));\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;\n }\n\n /// @notice Returns the \"synthetic\" tick which represents the price of the first entry in `tokens` in terms of the last\n /// @dev Useful for calculating relative prices along routes.\n /// @dev There must be one tick for each pairwise set of tokens.\n /// @param tokens The token contract addresses\n /// @param ticks The ticks, representing the price of each token pair in `tokens`\n /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`\n function getChainedPrice(address[] memory tokens, int24[] memory ticks)\n internal\n pure\n returns (int256 syntheticTick)\n {\n require(tokens.length - 1 == ticks.length, 'DL');\n for (uint256 i = 1; i <= ticks.length; i++) {\n // check the tokens for address sort order, then accumulate the\n // ticks into the running synthetic tick, ensuring that intermediate tokens \"cancel out\"\n tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/Path.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport './BytesLib.sol';\n\n/// @title Functions for manipulating path data for multihop swaps\nlibrary Path {\n using BytesLib for bytes;\n\n /// @dev The length of the bytes encoded address\n uint256 private constant ADDR_SIZE = 20;\n /// @dev The length of the bytes encoded fee\n uint256 private constant FEE_SIZE = 3;\n\n /// @dev The offset of a single token address and pool fee\n uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\n /// @dev The offset of an encoded pool key\n uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;\n /// @dev The minimum length of an encoding that contains 2 or more pools\n uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;\n\n /// @notice Returns true iff the path contains two or more pools\n /// @param path The encoded swap path\n /// @return True if path contains two or more pools, otherwise false\n function hasMultiplePools(bytes memory path) internal pure returns (bool) {\n return path.length >= MULTIPLE_POOLS_MIN_LENGTH;\n }\n\n /// @notice Returns the number of pools in the path\n /// @param path The encoded swap path\n /// @return The number of pools in the path\n function numPools(bytes memory path) internal pure returns (uint256) {\n // Ignore the first token address. From then on every fee and token offset indicates a pool.\n return ((path.length - ADDR_SIZE) / NEXT_OFFSET);\n }\n\n /// @notice Decodes the first pool in path\n /// @param path The bytes encoded swap path\n /// @return tokenA The first token of the given pool\n /// @return tokenB The second token of the given pool\n /// @return fee The fee level of the pool\n function decodeFirstPool(bytes memory path)\n internal\n pure\n returns (\n address tokenA,\n address tokenB,\n uint24 fee\n )\n {\n tokenA = path.toAddress(0);\n fee = path.toUint24(ADDR_SIZE);\n tokenB = path.toAddress(NEXT_OFFSET);\n }\n\n /// @notice Gets the segment corresponding to the first pool in the path\n /// @param path The bytes encoded swap path\n /// @return The segment containing all data necessary to target the first pool in the path\n function getFirstPool(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(0, POP_OFFSET);\n }\n\n /// @notice Skips a token + fee element from the buffer and returns the remainder\n /// @param path The swap path\n /// @return The remaining token + fee elements in the path\n function skipToken(bytes memory path) internal pure returns (bytes memory) {\n return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);\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/PoolTicksCounter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\n\nlibrary PoolTicksCounter {\n /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.\n /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the\n /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do\n /// want to count tickAfter. The opposite is true if we are swapping downwards.\n function countInitializedTicksCrossed(\n IUniswapV3Pool self,\n int24 tickBefore,\n int24 tickAfter\n ) internal view returns (uint32 initializedTicksCrossed) {\n int16 wordPosLower;\n int16 wordPosHigher;\n uint8 bitPosLower;\n uint8 bitPosHigher;\n bool tickBeforeInitialized;\n bool tickAfterInitialized;\n\n {\n // Get the key and offset in the tick bitmap of the active tick before and after the swap.\n int16 wordPos = int16((tickBefore / int24(self.tickSpacing())) >> 8);\n uint8 bitPos = uint8(int8((tickBefore / int24(self.tickSpacing())) % 256));\n\n int16 wordPosAfter = int16((tickAfter / int24(self.tickSpacing())) >> 8);\n uint8 bitPosAfter = uint8(int8((tickAfter / int24(self.tickSpacing())) % 256));\n\n // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.\n // If the initializable tick after the swap is initialized, our original tickAfter is a\n // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized\n // and we shouldn't count it.\n tickAfterInitialized =\n ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&\n ((tickAfter % self.tickSpacing()) == 0) &&\n (tickBefore > tickAfter);\n\n // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.\n // Use the same logic as above to decide whether we should count tickBefore or not.\n tickBeforeInitialized =\n ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&\n ((tickBefore % self.tickSpacing()) == 0) &&\n (tickBefore < tickAfter);\n\n if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {\n wordPosLower = wordPos;\n bitPosLower = bitPos;\n wordPosHigher = wordPosAfter;\n bitPosHigher = bitPosAfter;\n } else {\n wordPosLower = wordPosAfter;\n bitPosLower = bitPosAfter;\n wordPosHigher = wordPos;\n bitPosHigher = bitPos;\n }\n }\n\n // Count the number of initialized ticks crossed by iterating through the tick bitmap.\n // Our first mask should include the lower tick and everything to its left.\n uint256 mask = type(uint256).max << bitPosLower;\n while (wordPosLower <= wordPosHigher) {\n // If we're on the final tick bitmap page, ensure we only count up to our\n // ending tick.\n if (wordPosLower == wordPosHigher) {\n mask = mask & (type(uint256).max >> (255 - bitPosHigher));\n }\n\n uint256 masked = self.tickBitmap(wordPosLower) & mask;\n initializedTicksCrossed += countOneBits(masked);\n wordPosLower++;\n // Reset our mask so we consider all bits on the next iteration.\n mask = type(uint256).max;\n }\n\n if (tickAfterInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n if (tickBeforeInitialized) {\n initializedTicksCrossed -= 1;\n }\n\n return initializedTicksCrossed;\n }\n\n function countOneBits(uint256 x) private pure returns (uint16) {\n uint16 bits = 0;\n while (x != 0) {\n bits++;\n x &= (x - 1);\n }\n return bits;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PositionKey.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nlibrary PositionKey {\n /// @dev Returns the key of the position in the core library\n function compute(\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(owner, tickLower, tickUpper));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TokenRatioSortOrder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nlibrary TokenRatioSortOrder {\n int256 constant NUMERATOR_MOST = 300;\n int256 constant NUMERATOR_MORE = 200;\n int256 constant NUMERATOR = 100;\n\n int256 constant DENOMINATOR_MOST = -300;\n int256 constant DENOMINATOR_MORE = -200;\n int256 constant DENOMINATOR = -100;\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/PoolTickBitmap.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {BitMath} from \"./core/libraries/BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary PoolTickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(uint24(tick % 256));\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param pool Uniswap v3 pool interface\n /// @param tickSpacing the tick spacing of the pool\n /// @param tick The starting tick\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(IUniswapV3Pool pool, int24 tickSpacing, int24 tick, bool lte)\n internal\n view\n returns (int24 next, bool initialized)\n {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = pool.tickBitmap(wordPos) & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}" + }, + "contracts/libraries/uniswap/QuoterMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n\nimport {IUniswapV3Pool} from \"./core/interfaces/IUniswapV3Pool.sol\";\nimport {IQuoter} from \"./periphery/interfaces/IQuoter.sol\";\n\nimport {SwapMath} from \"./SwapMath.sol\";\nimport {FullMath} from \"./FullMath.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nimport \"./core/libraries/LowGasSafeMath.sol\";\nimport \"./core/libraries/SafeCast.sol\";\nimport \"./periphery/libraries/Path.sol\";\nimport {SqrtPriceMath} from \"./SqrtPriceMath.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {PoolTickBitmap} from \"./PoolTickBitmap.sol\";\nimport {PoolAddress} from \"./periphery/libraries/PoolAddress.sol\";\n\nlibrary QuoterMath {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // tick spacing\n int24 tickSpacing;\n }\n\n // used for packing under the stack limit\n struct QuoteParams {\n bool zeroForOne;\n bool exactInput;\n uint24 fee;\n uint160 sqrtPriceLimitX96;\n }\n\n function fillSlot0(IUniswapV3Pool pool) private view returns (Slot0 memory slot0) {\n (slot0.sqrtPriceX96, slot0.tick,,,,,) = pool.slot0();\n slot0.tickSpacing = pool.tickSpacing();\n\n return slot0;\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @notice Utility function called by the quote functions to\n /// calculate the amounts in/out for a v3 swap\n /// @param pool the Uniswap v3 pool interface\n /// @param amount the input amount calculated\n /// @param quoteParams a packed dataset of flags/inputs used to get around stack limit\n /// @return amount0 the amount of token0 sent in or out of the pool\n /// @return amount1 the amount of token1 sent in or out of the pool\n /// @return sqrtPriceAfterX96 the price of the pool after the swap\n /// @return initializedTicksCrossed the number of initialized ticks LOADED IN\n function quote(IUniswapV3Pool pool, int256 amount, QuoteParams memory quoteParams)\n internal\n view\n returns (int256 amount0, int256 amount1, uint160 sqrtPriceAfterX96, uint32 initializedTicksCrossed)\n {\n quoteParams.exactInput = amount > 0;\n initializedTicksCrossed = 1;\n\n Slot0 memory slot0 = fillSlot0(pool);\n\n SwapState memory state = SwapState({\n amountSpecifiedRemaining: amount,\n amountCalculated: 0,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n feeGrowthGlobalX128: 0,\n protocolFee: 0,\n liquidity: pool.liquidity()\n });\n\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != quoteParams.sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = PoolTickBitmap.nextInitializedTickWithinOneWord(\n pool, slot0.tickSpacing, state.tick, quoteParams.zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (\n quoteParams.zeroForOne\n ? step.sqrtPriceNextX96 < quoteParams.sqrtPriceLimitX96\n : step.sqrtPriceNextX96 > quoteParams.sqrtPriceLimitX96\n ) ? quoteParams.sqrtPriceLimitX96 : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n quoteParams.fee\n );\n\n if (quoteParams.exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n (, int128 liquidityNet,,,,,,) = pool.ticks(step.tickNext);\n\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (quoteParams.zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n\n initializedTicksCrossed++;\n }\n\n state.tick = quoteParams.zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n (amount0, amount1) = quoteParams.zeroForOne == quoteParams.exactInput\n ? (amount - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amount - state.amountSpecifiedRemaining);\n\n sqrtPriceAfterX96 = state.sqrtPriceX96;\n }\n}" + }, + "contracts/libraries/uniswap/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './core/libraries/LowGasSafeMath.sol';\nimport './core/libraries/SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}" + }, + "contracts/libraries/uniswap/SwapMath.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\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/uniswap/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}" + }, + "contracts/libraries/UniswapPricingLibrary.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 UniswapPricingLibrary \n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\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 uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n //This is the token 1 per token 0 price\n uint256 sqrtPrice = FullMath.mulDiv(\n sqrtPriceX96,\n STANDARD_EXPANSION_FACTOR,\n 2**96\n );\n\n uint256 sqrtPriceInverse = (STANDARD_EXPANSION_FACTOR *\n STANDARD_EXPANSION_FACTOR) / sqrtPrice;\n\n uint256 price = _poolRouteConfig.zeroForOne\n ? sqrtPrice * sqrtPrice\n : sqrtPriceInverse * sqrtPriceInverse;\n\n return price / STANDARD_EXPANSION_FACTOR;\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/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\n \n \n// Libraries \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 /**\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). Taken directly from uniswap oracle lib \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/MarketLiquidityRewards.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./interfaces/IMarketLiquidityRewards.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\n\nimport { BidState } from \"./TellerV2Storage.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/*\n- Allocate and claim rewards for loans based on bidId \n\n- Anyone can allocate rewards and an allocation has specific parameters that can be set to incentivise certain types of loans\n \n*/\n\ncontract MarketLiquidityRewards is IMarketLiquidityRewards, Initializable {\n address immutable tellerV2;\n address immutable marketRegistry;\n address immutable collateralManager;\n\n uint256 allocationCount;\n\n //allocationId => rewardAllocation\n mapping(uint256 => RewardAllocation) public allocatedRewards;\n\n //bidId => allocationId => rewardWasClaimed\n mapping(uint256 => mapping(uint256 => bool)) public rewardClaimedForBid;\n\n modifier onlyMarketOwner(uint256 _marketId) {\n require(\n msg.sender ==\n IMarketRegistry(marketRegistry).getMarketOwner(_marketId),\n \"Only market owner can call this function.\"\n );\n _;\n }\n\n event CreatedAllocation(\n uint256 allocationId,\n address allocator,\n uint256 marketId\n );\n\n event UpdatedAllocation(uint256 allocationId);\n\n event IncreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DecreasedAllocation(uint256 allocationId, uint256 amount);\n\n event DeletedAllocation(uint256 allocationId);\n\n event ClaimedRewards(\n uint256 allocationId,\n uint256 bidId,\n address recipient,\n uint256 amount\n );\n\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _collateralManager\n ) {\n tellerV2 = _tellerV2;\n marketRegistry = _marketRegistry;\n collateralManager = _collateralManager;\n }\n\n function initialize() external initializer {}\n\n /**\n * @notice Creates a new token allocation and transfers the token amount into escrow in this contract\n * @param _allocation - The RewardAllocation struct data to create\n * @return allocationId_\n */\n function allocateRewards(RewardAllocation calldata _allocation)\n public\n virtual\n returns (uint256 allocationId_)\n {\n allocationId_ = allocationCount++;\n\n require(\n _allocation.allocator == msg.sender,\n \"Invalid allocator address\"\n );\n\n require(\n _allocation.requiredPrincipalTokenAddress != address(0),\n \"Invalid required principal token address\"\n );\n\n IERC20Upgradeable(_allocation.rewardTokenAddress).transferFrom(\n msg.sender,\n address(this),\n _allocation.rewardTokenAmount\n );\n\n allocatedRewards[allocationId_] = _allocation;\n\n emit CreatedAllocation(\n allocationId_,\n _allocation.allocator,\n _allocation.marketId\n );\n }\n\n /**\n * @notice Allows the allocator to update properties of an allocation\n * @param _allocationId - The id for the allocation\n * @param _minimumCollateralPerPrincipalAmount - The required collateralization ratio\n * @param _rewardPerLoanPrincipalAmount - The reward to give per principal amount\n * @param _bidStartTimeMin - The block timestamp that loans must have been accepted after to claim rewards\n * @param _bidStartTimeMax - The block timestamp that loans must have been accepted before to claim rewards\n */\n function updateAllocation(\n uint256 _allocationId,\n uint256 _minimumCollateralPerPrincipalAmount,\n uint256 _rewardPerLoanPrincipalAmount,\n uint32 _bidStartTimeMin,\n uint32 _bidStartTimeMax\n ) public virtual {\n RewardAllocation storage allocation = allocatedRewards[_allocationId];\n\n require(\n msg.sender == allocation.allocator,\n \"Only the allocator can update allocation rewards.\"\n );\n\n allocation\n .minimumCollateralPerPrincipalAmount = _minimumCollateralPerPrincipalAmount;\n allocation.rewardPerLoanPrincipalAmount = _rewardPerLoanPrincipalAmount;\n allocation.bidStartTimeMin = _bidStartTimeMin;\n allocation.bidStartTimeMax = _bidStartTimeMax;\n\n emit UpdatedAllocation(_allocationId);\n }\n\n /**\n * @notice Allows anyone to add tokens to an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to add\n */\n function increaseAllocationAmount(\n uint256 _allocationId,\n uint256 _tokenAmount\n ) public virtual {\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transferFrom(msg.sender, address(this), _tokenAmount);\n allocatedRewards[_allocationId].rewardTokenAmount += _tokenAmount;\n\n emit IncreasedAllocation(_allocationId, _tokenAmount);\n }\n\n /**\n * @notice Allows the allocator to withdraw some or all of the funds within an allocation\n * @param _allocationId - The id for the allocation\n * @param _tokenAmount - The amount of tokens to withdraw\n */\n function deallocateRewards(uint256 _allocationId, uint256 _tokenAmount)\n public\n virtual\n {\n require(\n msg.sender == allocatedRewards[_allocationId].allocator,\n \"Only the allocator can deallocate rewards.\"\n );\n\n //enforce that the token amount withdraw must be LEQ to the reward amount for this allocation\n if (_tokenAmount > allocatedRewards[_allocationId].rewardTokenAmount) {\n _tokenAmount = allocatedRewards[_allocationId].rewardTokenAmount;\n }\n\n //subtract amount reward before transfer\n _decrementAllocatedAmount(_allocationId, _tokenAmount);\n\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(msg.sender, _tokenAmount);\n\n //if the allocated rewards are drained completely, delete the storage slot for it\n if (allocatedRewards[_allocationId].rewardTokenAmount == 0) {\n delete allocatedRewards[_allocationId];\n\n emit DeletedAllocation(_allocationId);\n } else {\n emit DecreasedAllocation(_allocationId, _tokenAmount);\n }\n }\n\n struct LoanSummary {\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 _getLoanSummary(uint256 _bidId)\n internal\n returns (LoanSummary memory _summary)\n {\n (\n _summary.borrower,\n _summary.lender,\n _summary.marketId,\n _summary.principalTokenAddress,\n _summary.principalAmount,\n _summary.acceptedTimestamp,\n _summary.lastRepaidTimestamp,\n _summary.bidState\n ) = ITellerV2(tellerV2).getLoanSummary(_bidId);\n }\n\n /**\n * @notice Allows a borrower or lender to withdraw the allocated ERC20 reward for their loan\n * @param _allocationId - The id for the reward allocation\n * @param _bidId - The id for the loan. Each loan only grants one reward per allocation.\n */\n function claimRewards(uint256 _allocationId, uint256 _bidId)\n external\n virtual\n {\n RewardAllocation storage allocatedReward = allocatedRewards[\n _allocationId\n ];\n\n //set a flag that this reward was claimed for this bid to defend against re-entrancy\n require(\n !rewardClaimedForBid[_bidId][_allocationId],\n \"reward already claimed\"\n );\n rewardClaimedForBid[_bidId][_allocationId] = true;\n\n //make this a struct ?\n LoanSummary memory loanSummary = _getLoanSummary(_bidId); //ITellerV2(tellerV2).getLoanSummary(_bidId);\n\n address collateralTokenAddress = allocatedReward\n .requiredCollateralTokenAddress;\n\n //require that the loan was started in the correct timeframe\n _verifyLoanStartTime(\n loanSummary.acceptedTimestamp,\n allocatedReward.bidStartTimeMin,\n allocatedReward.bidStartTimeMax\n );\n\n //if a collateral token address is set on the allocation, verify that the bid has enough collateral ratio\n if (collateralTokenAddress != address(0)) {\n uint256 collateralAmount = ICollateralManager(collateralManager)\n .getCollateralAmount(_bidId, collateralTokenAddress);\n\n //require collateral amount\n _verifyCollateralAmount(\n collateralTokenAddress,\n collateralAmount,\n loanSummary.principalTokenAddress,\n loanSummary.principalAmount,\n allocatedReward.minimumCollateralPerPrincipalAmount\n );\n }\n\n require(\n loanSummary.principalTokenAddress ==\n allocatedReward.requiredPrincipalTokenAddress,\n \"Principal token address mismatch for allocation\"\n );\n\n require(\n loanSummary.marketId == allocatedRewards[_allocationId].marketId,\n \"MarketId mismatch for allocation\"\n );\n\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n loanSummary.principalTokenAddress\n ).decimals();\n\n address rewardRecipient = _verifyAndReturnRewardRecipient(\n allocatedReward.allocationStrategy,\n loanSummary.bidState,\n loanSummary.borrower,\n loanSummary.lender\n );\n\n uint32 loanDuration = loanSummary.lastRepaidTimestamp -\n loanSummary.acceptedTimestamp;\n\n uint256 amountToReward = _calculateRewardAmount(\n loanSummary.principalAmount,\n loanDuration,\n principalTokenDecimals,\n allocatedReward.rewardPerLoanPrincipalAmount\n );\n\n if (amountToReward > allocatedReward.rewardTokenAmount) {\n amountToReward = allocatedReward.rewardTokenAmount;\n }\n\n require(amountToReward > 0, \"Nothing to claim.\");\n\n _decrementAllocatedAmount(_allocationId, amountToReward);\n\n //transfer tokens reward to the msgsender\n IERC20Upgradeable(allocatedRewards[_allocationId].rewardTokenAddress)\n .transfer(rewardRecipient, amountToReward);\n\n emit ClaimedRewards(\n _allocationId,\n _bidId,\n rewardRecipient,\n amountToReward\n );\n }\n\n /**\n * @notice Verifies that the bid state is appropriate for claiming rewards based on the allocation strategy and then returns the address of the reward recipient(borrower or lender)\n * @param _strategy - The strategy for the reward allocation.\n * @param _bidState - The bid state of the loan.\n * @param _borrower - The borrower of the loan.\n * @param _lender - The lender of the loan.\n * @return rewardRecipient_ The address that will receive the rewards. Either the borrower or lender.\n */\n function _verifyAndReturnRewardRecipient(\n AllocationStrategy _strategy,\n BidState _bidState,\n address _borrower,\n address _lender\n ) internal virtual returns (address rewardRecipient_) {\n if (_strategy == AllocationStrategy.BORROWER) {\n require(_bidState == BidState.PAID, \"Invalid bid state for loan.\");\n\n rewardRecipient_ = _borrower;\n } else if (_strategy == AllocationStrategy.LENDER) {\n //Loan must have been accepted in the past\n require(\n _bidState >= BidState.ACCEPTED,\n \"Invalid bid state for loan.\"\n );\n\n rewardRecipient_ = _lender;\n } else {\n revert(\"Unknown allocation strategy\");\n }\n }\n\n /**\n * @notice Decrements the amount allocated to keep track of tokens in escrow\n * @param _allocationId - The id for the allocation to decrement\n * @param _amount - The amount of ERC20 to decrement\n */\n function _decrementAllocatedAmount(uint256 _allocationId, uint256 _amount)\n internal\n {\n allocatedRewards[_allocationId].rewardTokenAmount -= _amount;\n }\n\n /**\n * @notice Calculates the reward to claim for the allocation\n * @param _loanPrincipal - The amount of principal for the loan for which to reward\n * @param _loanDuration - The duration of the loan in seconds\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _rewardPerLoanPrincipalAmount - The amount of reward per loan principal amount, expanded by the principal token decimals\n * @return The amount of ERC20 to reward\n */\n function _calculateRewardAmount(\n uint256 _loanPrincipal,\n uint256 _loanDuration,\n uint256 _principalTokenDecimals,\n uint256 _rewardPerLoanPrincipalAmount\n ) internal view returns (uint256) {\n uint256 rewardPerYear = MathUpgradeable.mulDiv(\n _loanPrincipal,\n _rewardPerLoanPrincipalAmount, //expanded by principal token decimals\n 10**_principalTokenDecimals\n );\n\n return MathUpgradeable.mulDiv(rewardPerYear, _loanDuration, 365 days);\n }\n\n /**\n * @notice Verifies that the collateral ratio for the loan was sufficient based on _minimumCollateralPerPrincipalAmount of the allocation\n * @param _collateralTokenAddress - The contract address for the collateral token\n * @param _collateralAmount - The number of decimals of the collateral token\n * @param _principalTokenAddress - The contract address for the principal token\n * @param _principalAmount - The number of decimals of the principal token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _verifyCollateralAmount(\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n address _principalTokenAddress,\n uint256 _principalAmount,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal virtual {\n uint256 principalTokenDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n uint256 collateralTokenDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n\n uint256 minCollateral = _requiredCollateralAmount(\n _principalAmount,\n principalTokenDecimals,\n collateralTokenDecimals,\n _minimumCollateralPerPrincipalAmount\n );\n\n require(\n _collateralAmount >= minCollateral,\n \"Loan does not meet minimum collateralization ratio.\"\n );\n }\n\n /**\n * @notice Calculates the minimum amount of collateral the loan requires based on principal amount\n * @param _principalAmount - The number of decimals of the principal token\n * @param _principalTokenDecimals - The number of decimals of the principal token\n * @param _collateralTokenDecimals - The number of decimals of the collateral token\n * @param _minimumCollateralPerPrincipalAmount - The amount of collateral required per principal amount. Expanded by the principal token decimals and collateral token decimals.\n */\n function _requiredCollateralAmount(\n uint256 _principalAmount,\n uint256 _principalTokenDecimals,\n uint256 _collateralTokenDecimals,\n uint256 _minimumCollateralPerPrincipalAmount\n ) internal view virtual returns (uint256) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n _minimumCollateralPerPrincipalAmount, //expanded by principal token decimals and collateral token decimals\n 10**(_principalTokenDecimals + _collateralTokenDecimals)\n );\n }\n\n /**\n * @notice Verifies that the loan start time is within the bounds set by the allocation requirements\n * @param _loanStartTime - The timestamp when the loan was accepted\n * @param _minStartTime - The minimum time required, after which the loan must have been accepted\n * @param _maxStartTime - The maximum time required, before which the loan must have been accepted\n */\n function _verifyLoanStartTime(\n uint32 _loanStartTime,\n uint32 _minStartTime,\n uint32 _maxStartTime\n ) internal virtual {\n require(\n _minStartTime == 0 || _loanStartTime > _minStartTime,\n \"Loan was accepted before the min start time.\"\n );\n require(\n _maxStartTime == 0 || _loanStartTime < _maxStartTime,\n \"Loan was accepted after the max start time.\"\n );\n }\n\n /**\n * @notice Returns the amount of reward tokens remaining in the allocation\n * @param _allocationId - The id for the allocation\n */\n function getRewardTokenAmount(uint256 _allocationId)\n public\n view\n override\n returns (uint256)\n {\n return allocatedRewards[_allocationId].rewardTokenAmount;\n }\n}\n" + }, + "contracts/MarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"./EAS/TellerAS.sol\";\nimport \"./EAS/TellerASResolver.sol\";\n\n//must continue to use this so storage slots are not broken\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\n\n// Libraries\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { PaymentType } from \"./libraries/V2Calculations.sol\";\n\ncontract MarketRegistry is\n IMarketRegistry,\n Initializable,\n Context,\n TellerASResolver\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /** Constant Variables **/\n\n uint256 public constant CURRENT_CODE_VERSION = 8;\n uint256 public constant MAX_MARKET_FEE_PERCENT = 1000;\n\n /* Storage Variables */\n\n struct Marketplace {\n address owner;\n string metadataURI;\n uint16 marketplaceFeePercent; // 10000 is 100%\n bool lenderAttestationRequired;\n EnumerableSet.AddressSet verifiedLendersForMarket;\n mapping(address => bytes32) lenderAttestationIds;\n uint32 paymentCycleDuration; // unix time (seconds)\n uint32 paymentDefaultDuration; //unix time\n uint32 bidExpirationTime; //unix time\n bool borrowerAttestationRequired;\n EnumerableSet.AddressSet verifiedBorrowersForMarket;\n mapping(address => bytes32) borrowerAttestationIds;\n address feeRecipient;\n PaymentType paymentType;\n PaymentCycleType paymentCycleType;\n }\n\n bytes32 public lenderAttestationSchemaId;\n\n mapping(uint256 => Marketplace) internal markets;\n mapping(bytes32 => uint256) internal __uriToId; //DEPRECATED\n uint256 public marketCount;\n bytes32 private _attestingSchemaId;\n bytes32 public borrowerAttestationSchemaId;\n\n uint256 public version;\n\n mapping(uint256 => bool) private marketIsClosed;\n\n TellerAS public tellerAS;\n\n /* Modifiers */\n\n modifier ownsMarket(uint256 _marketId) {\n require(_getMarketOwner(_marketId) == _msgSender(), \"Not the owner\");\n _;\n }\n\n modifier withAttestingSchema(bytes32 schemaId) {\n _attestingSchemaId = schemaId;\n _;\n _attestingSchemaId = bytes32(0);\n }\n\n /* Events */\n\n event MarketCreated(address indexed owner, uint256 marketId);\n event SetMarketURI(uint256 marketId, string uri);\n event SetPaymentCycleDuration(uint256 marketId, uint32 duration); // DEPRECATED - used for subgraph reference\n event SetPaymentCycle(\n uint256 marketId,\n PaymentCycleType paymentCycleType,\n uint32 value\n );\n event SetPaymentDefaultDuration(uint256 marketId, uint32 duration);\n event SetBidExpirationTime(uint256 marketId, uint32 duration);\n event SetMarketFee(uint256 marketId, uint16 feePct);\n event LenderAttestation(uint256 marketId, address lender);\n event BorrowerAttestation(uint256 marketId, address borrower);\n event LenderRevocation(uint256 marketId, address lender);\n event BorrowerRevocation(uint256 marketId, address borrower);\n event MarketClosed(uint256 marketId);\n event LenderExitMarket(uint256 marketId, address lender);\n event BorrowerExitMarket(uint256 marketId, address borrower);\n event SetMarketOwner(uint256 marketId, address newOwner);\n event SetMarketFeeRecipient(uint256 marketId, address newRecipient);\n event SetMarketLenderAttestation(uint256 marketId, bool required);\n event SetMarketBorrowerAttestation(uint256 marketId, bool required);\n event SetMarketPaymentType(uint256 marketId, PaymentType paymentType);\n\n /* External Functions */\n\n function initialize(TellerAS _tellerAS) external initializer {\n tellerAS = _tellerAS;\n\n lenderAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address lenderAddress)\",\n this\n );\n borrowerAttestationSchemaId = tellerAS.getASRegistry().register(\n \"(uint256 marketId, address borrowerAddress)\",\n this\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n _paymentType,\n _paymentCycleType,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @dev Uses the default EMI payment type.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _uri URI string to get metadata details about the market.\n * @return marketId_ The market ID of the newly created market.\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 marketId_ = _createMarket(\n _initialOwner,\n _paymentCycleDuration,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireLenderAttestation,\n _requireBorrowerAttestation,\n PaymentType.EMI,\n PaymentCycleType.Seconds,\n _uri\n );\n }\n\n /**\n * @notice Creates a new market.\n * @param _initialOwner Address who will initially own the market.\n * @param _paymentCycleDuration Length of time in seconds before a bid's next payment is required to be made.\n * @param _paymentDefaultDuration Length of time in seconds before a loan is considered in default for non-payment.\n * @param _bidExpirationTime Length of time in seconds before pending bids expire.\n * @param _requireLenderAttestation Boolean that indicates if lenders require attestation to join market.\n * @param _requireBorrowerAttestation Boolean that indicates if borrowers require attestation to join market.\n * @param _paymentType The payment type for loans in the market.\n * @param _uri URI string to get metadata details about the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @return marketId_ The market ID of the newly created market.\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 ) internal returns (uint256 marketId_) {\n require(_initialOwner != address(0), \"Invalid owner address\");\n // Increment market ID counter\n marketId_ = ++marketCount;\n\n // Set the market owner\n markets[marketId_].owner = _initialOwner;\n\n // Initialize market settings\n _setMarketSettings(\n marketId_,\n _paymentCycleDuration,\n _paymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _requireBorrowerAttestation,\n _requireLenderAttestation,\n _uri\n );\n\n emit MarketCreated(_initialOwner, marketId_);\n }\n\n /**\n * @notice Closes a market so new bids cannot be added.\n * @param _marketId The market ID for the market to close.\n */\n\n function closeMarket(uint256 _marketId) public ownsMarket(_marketId) {\n if (!marketIsClosed[_marketId]) {\n marketIsClosed[_marketId] = true;\n\n emit MarketClosed(_marketId);\n }\n }\n\n /**\n * @notice Returns the status of a market existing and not being closed.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketOpen(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return\n markets[_marketId].owner != address(0) &&\n !marketIsClosed[_marketId];\n }\n\n /**\n * @notice Returns the status of a market being open or closed for new bids. Does not indicate whether or not a market exists.\n * @param _marketId The market ID for the market to check.\n */\n function isMarketClosed(uint256 _marketId)\n public\n view\n override\n returns (bool)\n {\n return marketIsClosed[_marketId];\n }\n\n /**\n * @notice Adds a lender to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _lenderAddress, _expirationTime, true);\n }\n\n /**\n * @notice Adds a lender to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestLender(\n uint256 _marketId,\n address _lenderAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n _expirationTime,\n true,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a lender from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeLender(uint256 _marketId, address _lenderAddress) external {\n _revokeStakeholder(_marketId, _lenderAddress, true);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeLender(\n uint256 _marketId,\n address _lenderAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _lenderAddress,\n true,\n _v,\n _r,\n _s\n );\n } */\n\n /**\n * @notice Allows a lender to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function lenderExitMarket(uint256 _marketId) external {\n // Remove lender address from market set\n bool response = markets[_marketId].verifiedLendersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit LenderExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Adds a borrower to a market.\n * @dev See {_attestStakeholder}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime\n ) external {\n _attestStakeholder(_marketId, _borrowerAddress, _expirationTime, false);\n }\n\n /**\n * @notice Adds a borrower to a market via delegated attestation.\n * @dev See {_attestStakeholderViaDelegation}.\n */\n function attestBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint256 _expirationTime,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _attestStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n _expirationTime,\n false,\n _v,\n _r,\n _s\n );\n }\n\n /**\n * @notice Removes a borrower from an market.\n * @dev See {_revokeStakeholder}.\n */\n function revokeBorrower(uint256 _marketId, address _borrowerAddress)\n external\n {\n _revokeStakeholder(_marketId, _borrowerAddress, false);\n }\n\n /**\n * @notice Removes a borrower from a market via delegated revocation.\n * @dev See {_revokeStakeholderViaDelegation}.\n */\n /* function revokeBorrower(\n uint256 _marketId,\n address _borrowerAddress,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) external {\n _revokeStakeholderViaDelegation(\n _marketId,\n _borrowerAddress,\n false,\n _v,\n _r,\n _s\n );\n }*/\n\n /**\n * @notice Allows a borrower to voluntarily leave a market.\n * @param _marketId The market ID to leave.\n */\n function borrowerExitMarket(uint256 _marketId) external {\n // Remove borrower address from market set\n bool response = markets[_marketId].verifiedBorrowersForMarket.remove(\n _msgSender()\n );\n if (response) {\n emit BorrowerExitMarket(_marketId, _msgSender());\n }\n }\n\n /**\n * @notice Verifies an attestation is valid.\n * @dev This function must only be called by the `attestLender` function above.\n * @param recipient Lender's address who is being attested.\n * @param schema The schema used for the attestation.\n * @param data Data the must include the market ID and lender's address\n * @param\n * @param attestor Market owner's address who signed the attestation.\n * @return Boolean indicating the attestation was successful.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 /* expirationTime */,\n address attestor\n ) external payable override returns (bool) {\n bytes32 attestationSchemaId = keccak256(\n abi.encodePacked(schema, address(this))\n );\n (uint256 marketId, address lenderAddress) = abi.decode(\n data,\n (uint256, address)\n );\n return\n (_attestingSchemaId == attestationSchemaId &&\n recipient == lenderAddress &&\n attestor == _getMarketOwner(marketId)) ||\n attestor == address(this);\n }\n\n /**\n * @notice Transfers ownership of a marketplace.\n * @param _marketId The ID of a market.\n * @param _newOwner Address of the new market owner.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function transferMarketOwnership(uint256 _marketId, address _newOwner)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].owner = _newOwner;\n emit SetMarketOwner(_marketId, _newOwner);\n }\n\n /**\n * @notice Updates multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function updateMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) public ownsMarket(_marketId) {\n _setMarketSettings(\n _marketId,\n _paymentCycleDuration,\n _newPaymentType,\n _paymentCycleType,\n _paymentDefaultDuration,\n _bidExpirationTime,\n _feePercent,\n _borrowerAttestationRequired,\n _lenderAttestationRequired,\n _metadataURI\n );\n }\n\n /**\n * @notice Sets the fee recipient address for a market.\n * @param _marketId The ID of a market.\n * @param _recipient Address of the new fee recipient.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeeRecipient(uint256 _marketId, address _recipient)\n public\n ownsMarket(_marketId)\n {\n markets[_marketId].feeRecipient = _recipient;\n emit SetMarketFeeRecipient(_marketId, _recipient);\n }\n\n /**\n * @notice Sets the metadata URI for a market.\n * @param _marketId The ID of a market.\n * @param _uri A URI that points to a market's metadata.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketURI(uint256 _marketId, string calldata _uri)\n public\n ownsMarket(_marketId)\n {\n //We do string comparison by checking the hashes of the strings against one another\n if (\n keccak256(abi.encodePacked(_uri)) !=\n keccak256(abi.encodePacked(markets[_marketId].metadataURI))\n ) {\n markets[_marketId].metadataURI = _uri;\n\n emit SetMarketURI(_marketId, _uri);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn delinquent.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleType Cycle type (seconds or monthly)\n * @param _duration Delinquency duration for new loans\n */\n function setPaymentCycle(\n uint256 _marketId,\n PaymentCycleType _paymentCycleType,\n uint32 _duration\n ) public ownsMarket(_marketId) {\n require(\n (_paymentCycleType == PaymentCycleType.Seconds) ||\n (_paymentCycleType == PaymentCycleType.Monthly &&\n _duration == 0),\n \"monthly payment cycle duration cannot be set\"\n );\n Marketplace storage market = markets[_marketId];\n uint32 duration = _paymentCycleType == PaymentCycleType.Seconds\n ? _duration\n : 30 days;\n if (\n _paymentCycleType != market.paymentCycleType ||\n duration != market.paymentCycleDuration\n ) {\n markets[_marketId].paymentCycleType = _paymentCycleType;\n markets[_marketId].paymentCycleDuration = duration;\n\n emit SetPaymentCycle(_marketId, _paymentCycleType, duration);\n }\n }\n\n /**\n * @notice Sets the duration of new loans for this market before they turn defaulted.\n * @notice Changing this value does not change the terms of existing loans for this market.\n * @param _marketId The ID of a market.\n * @param _duration Default duration for new loans\n */\n function setPaymentDefaultDuration(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].paymentDefaultDuration) {\n markets[_marketId].paymentDefaultDuration = _duration;\n\n emit SetPaymentDefaultDuration(_marketId, _duration);\n }\n }\n\n function setBidExpirationTime(uint256 _marketId, uint32 _duration)\n public\n ownsMarket(_marketId)\n {\n if (_duration != markets[_marketId].bidExpirationTime) {\n markets[_marketId].bidExpirationTime = _duration;\n\n emit SetBidExpirationTime(_marketId, _duration);\n }\n }\n\n /**\n * @notice Sets the fee for the market.\n * @param _marketId The ID of a market.\n * @param _newPercent The percentage fee in basis points.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setMarketFeePercent(uint256 _marketId, uint16 _newPercent)\n public\n ownsMarket(_marketId)\n {\n \n require(\n _newPercent >= 0 && _newPercent <= MAX_MARKET_FEE_PERCENT,\n \"invalid fee percent\"\n );\n\n\n\n if (_newPercent != markets[_marketId].marketplaceFeePercent) {\n markets[_marketId].marketplaceFeePercent = _newPercent;\n emit SetMarketFee(_marketId, _newPercent);\n }\n }\n\n /**\n * @notice Set the payment type for the market.\n * @param _marketId The ID of the market.\n * @param _newPaymentType The payment type for the market.\n */\n function setMarketPaymentType(\n uint256 _marketId,\n PaymentType _newPaymentType\n ) public ownsMarket(_marketId) {\n if (_newPaymentType != markets[_marketId].paymentType) {\n markets[_marketId].paymentType = _newPaymentType;\n emit SetMarketPaymentType(_marketId, _newPaymentType);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for lenders.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setLenderAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].lenderAttestationRequired) {\n markets[_marketId].lenderAttestationRequired = _required;\n emit SetMarketLenderAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Enable/disables market whitelist for borrowers.\n * @param _marketId The ID of a market.\n * @param _required Boolean indicating if the market requires whitelist.\n *\n * Requirements:\n * - The caller must be the current owner.\n */\n function setBorrowerAttestationRequired(uint256 _marketId, bool _required)\n public\n ownsMarket(_marketId)\n {\n if (_required != markets[_marketId].borrowerAttestationRequired) {\n markets[_marketId].borrowerAttestationRequired = _required;\n emit SetMarketBorrowerAttestation(_marketId, _required);\n }\n }\n\n /**\n * @notice Gets the data associated with a market.\n * @param _marketId The ID of a market.\n */\n function getMarketData(uint256 _marketId)\n public\n view\n returns (\n address owner,\n uint32 paymentCycleDuration,\n uint32 paymentDefaultDuration,\n uint32 loanExpirationTime,\n string memory metadataURI,\n uint16 marketplaceFeePercent,\n bool lenderAttestationRequired\n )\n {\n return (\n markets[_marketId].owner,\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentDefaultDuration,\n markets[_marketId].bidExpirationTime,\n markets[_marketId].metadataURI,\n markets[_marketId].marketplaceFeePercent,\n markets[_marketId].lenderAttestationRequired\n );\n }\n\n /**\n * @notice Gets the attestation requirements for a given market.\n * @param _marketId The ID of the market.\n */\n function getMarketAttestationRequirements(uint256 _marketId)\n public\n view\n returns (\n bool lenderAttestationRequired,\n bool borrowerAttestationRequired\n )\n {\n return (\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].borrowerAttestationRequired\n );\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function getMarketOwner(uint256 _marketId)\n public\n view\n virtual\n override\n returns (address)\n {\n return _getMarketOwner(_marketId);\n }\n\n /**\n * @notice Gets the address of a market's owner.\n * @param _marketId The ID of a market.\n * @return The address of a market's owner.\n */\n function _getMarketOwner(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n return markets[_marketId].owner;\n }\n\n /**\n * @notice Gets the fee recipient of a market.\n * @param _marketId The ID of a market.\n * @return The address of a market's fee recipient.\n */\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n address recipient = markets[_marketId].feeRecipient;\n\n if (recipient == address(0)) {\n return _getMarketOwner(_marketId);\n }\n\n return recipient;\n }\n\n /**\n * @notice Gets the metadata URI of a market.\n * @param _marketId The ID of a market.\n * @return URI of a market's metadata.\n */\n function getMarketURI(uint256 _marketId)\n public\n view\n override\n returns (string memory)\n {\n return markets[_marketId].metadataURI;\n }\n\n /**\n * @notice Gets the loan delinquent duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan until it is delinquent.\n * @return The type of payment cycle for loans in the market.\n */\n function getPaymentCycle(uint256 _marketId)\n public\n view\n override\n returns (uint32, PaymentCycleType)\n {\n return (\n markets[_marketId].paymentCycleDuration,\n markets[_marketId].paymentCycleType\n );\n }\n\n /**\n * @notice Gets the loan default duration of a market.\n * @param _marketId The ID of a market.\n * @return Duration of a loan repayment interval until it is default.\n */\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[_marketId].paymentDefaultDuration;\n }\n\n /**\n * @notice Get the payment type of a market.\n * @param _marketId the ID of the market.\n * @return The type of payment for loans in the market.\n */\n function getPaymentType(uint256 _marketId)\n public\n view\n override\n returns (PaymentType)\n {\n return markets[_marketId].paymentType;\n }\n\n function getBidExpirationTime(uint256 marketId)\n public\n view\n override\n returns (uint32)\n {\n return markets[marketId].bidExpirationTime;\n }\n\n /**\n * @notice Gets the marketplace fee in basis points\n * @param _marketId The ID of a market.\n * @return fee in basis points\n */\n function getMarketplaceFee(uint256 _marketId)\n public\n view\n override\n returns (uint16 fee)\n {\n return markets[_marketId].marketplaceFeePercent;\n }\n\n /**\n * @notice Checks if a lender has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _lenderAddress Address to check.\n * @return isVerified_ Boolean indicating if a lender has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the lender.\n */\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _lenderAddress,\n markets[_marketId].lenderAttestationRequired,\n markets[_marketId].lenderAttestationIds,\n markets[_marketId].verifiedLendersForMarket\n );\n }\n\n /**\n * @notice Checks if a borrower has been attested and added to a market.\n * @param _marketId The ID of a market.\n * @param _borrowerAddress Address of the borrower to check.\n * @return isVerified_ Boolean indicating if a borrower has been added to a market.\n * @return uuid_ Bytes32 representing the UUID of the borrower.\n */\n function isVerifiedBorrower(uint256 _marketId, address _borrowerAddress)\n public\n view\n override\n returns (bool isVerified_, bytes32 uuid_)\n {\n return\n _isVerified(\n _borrowerAddress,\n markets[_marketId].borrowerAttestationRequired,\n markets[_marketId].borrowerAttestationIds,\n markets[_marketId].verifiedBorrowersForMarket\n );\n }\n\n /**\n * @notice Gets addresses of all attested lenders.\n * @param _marketId The ID of a market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedLendersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedLendersForMarket;\n\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Gets addresses of all attested borrowers.\n * @param _marketId The ID of the market.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return Array of addresses that have been added to a market.\n */\n function getAllVerifiedBorrowersForMarket(\n uint256 _marketId,\n uint256 _page,\n uint256 _perPage\n ) public view returns (address[] memory) {\n EnumerableSet.AddressSet storage set = markets[_marketId]\n .verifiedBorrowersForMarket;\n return _getStakeholdersForMarket(set, _page, _perPage);\n }\n\n /**\n * @notice Sets multiple market settings for a given market.\n * @param _marketId The ID of a market.\n * @param _paymentCycleDuration Delinquency duration for new loans\n * @param _newPaymentType The payment type for the market.\n * @param _paymentCycleType The payment cycle type for loans in the market - Seconds or Monthly\n * @param _paymentDefaultDuration Default duration for new loans\n * @param _bidExpirationTime Duration of time before a bid is considered out of date\n * @param _metadataURI A URI that points to a market's metadata.\n */\n function _setMarketSettings(\n uint256 _marketId,\n uint32 _paymentCycleDuration,\n PaymentType _newPaymentType,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _borrowerAttestationRequired,\n bool _lenderAttestationRequired,\n string calldata _metadataURI\n ) internal {\n setMarketURI(_marketId, _metadataURI);\n setPaymentDefaultDuration(_marketId, _paymentDefaultDuration);\n setBidExpirationTime(_marketId, _bidExpirationTime);\n setMarketFeePercent(_marketId, _feePercent);\n setLenderAttestationRequired(_marketId, _lenderAttestationRequired);\n setBorrowerAttestationRequired(_marketId, _borrowerAttestationRequired);\n setMarketPaymentType(_marketId, _newPaymentType);\n setPaymentCycle(_marketId, _paymentCycleType, _paymentCycleDuration);\n }\n\n /**\n * @notice Gets addresses of all attested relevant stakeholders.\n * @param _set The stored set of stakeholders to index from.\n * @param _page Page index to start from.\n * @param _perPage Number of items in a page to return.\n * @return stakeholders_ Array of addresses that have been added to a market.\n */\n function _getStakeholdersForMarket(\n EnumerableSet.AddressSet storage _set,\n uint256 _page,\n uint256 _perPage\n ) internal view returns (address[] memory stakeholders_) {\n uint256 len = _set.length();\n\n uint256 start = _page * _perPage;\n if (start <= len) {\n uint256 end = start + _perPage;\n // Ensure we do not go out of bounds\n if (end > len) {\n end = len;\n }\n\n stakeholders_ = new address[](end - start);\n for (uint256 i = start; i < end; i++) {\n stakeholders_[i] = _set.at(i);\n }\n }\n }\n\n /* Internal Functions */\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market.\n * @param _marketId The market ID to add a borrower to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n // Submit attestation for borrower to join a market\n bytes32 uuid = tellerAS.attest(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n abi.encode(_marketId, _stakeholderAddress)\n );\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (lender or borrower) to a market via delegated attestation.\n * @dev The signature must match that of the market owner.\n * @param _marketId The market ID to add a lender to.\n * @param _stakeholderAddress The address of the lender to add to the market.\n * @param _expirationTime The expiration time of the attestation.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @param _v Signature value\n * @param _r Signature value\n * @param _s Signature value\n */\n function _attestStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n uint256 _expirationTime,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n virtual\n withAttestingSchema(\n _isLender ? lenderAttestationSchemaId : borrowerAttestationSchemaId\n )\n {\n // NOTE: block scope to prevent stack too deep!\n bytes32 uuid;\n {\n bytes memory data = abi.encode(_marketId, _stakeholderAddress);\n address attestor = _getMarketOwner(_marketId);\n // Submit attestation for stakeholder to join a market (attestation must be signed by market owner)\n uuid = tellerAS.attestByDelegation(\n _stakeholderAddress,\n _attestingSchemaId, // set by the modifier\n _expirationTime,\n 0,\n data,\n attestor,\n _v,\n _r,\n _s\n );\n }\n _attestStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n uuid,\n _isLender\n );\n }\n\n /**\n * @notice Adds a stakeholder (borrower/lender) to a market.\n * @param _marketId The market ID to add a stakeholder to.\n * @param _stakeholderAddress The address of the stakeholder to add to the market.\n * @param _uuid The UUID of the attestation created.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _attestStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bytes32 _uuid,\n bool _isLender\n ) internal virtual {\n if (_isLender) {\n // Store the lender attestation ID for the market ID\n markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedLendersForMarket.add(\n _stakeholderAddress\n );\n\n emit LenderAttestation(_marketId, _stakeholderAddress);\n } else {\n // Store the lender attestation ID for the market ID\n markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ] = _uuid;\n // Add lender address to market set\n markets[_marketId].verifiedBorrowersForMarket.add(\n _stakeholderAddress\n );\n\n emit BorrowerAttestation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Removes a stakeholder from an market.\n * @dev The caller must be the market owner.\n * @param _marketId The market ID to remove the borrower from.\n * @param _stakeholderAddress The address of the borrower to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n */\n function _revokeStakeholder(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual {\n require(\n _msgSender() == _getMarketOwner(_marketId),\n \"Not the market owner\"\n );\n\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // tellerAS.revoke(uuid);\n }\n\n \n /* function _revokeStakeholderViaDelegation(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal {\n bytes32 uuid = _revokeStakeholderVerification(\n _marketId,\n _stakeholderAddress,\n _isLender\n );\n // NOTE: Disabling the call to revoke the attestation on EAS contracts\n // address attestor = markets[_marketId].owner;\n // tellerAS.revokeByDelegation(uuid, attestor, _v, _r, _s);\n } */\n\n /**\n * @notice Removes a stakeholder (borrower/lender) from a market.\n * @param _marketId The market ID to remove the lender from.\n * @param _stakeholderAddress The address of the stakeholder to remove from the market.\n * @param _isLender Boolean indicating if the stakeholder is a lender. Otherwise it is a borrower.\n * @return uuid_ The ID of the previously verified attestation.\n */\n function _revokeStakeholderVerification(\n uint256 _marketId,\n address _stakeholderAddress,\n bool _isLender\n ) internal virtual returns (bytes32 uuid_) {\n if (_isLender) {\n uuid_ = markets[_marketId].lenderAttestationIds[\n _stakeholderAddress\n ];\n // Remove lender address from market set\n markets[_marketId].verifiedLendersForMarket.remove(\n _stakeholderAddress\n );\n\n emit LenderRevocation(_marketId, _stakeholderAddress);\n } else {\n uuid_ = markets[_marketId].borrowerAttestationIds[\n _stakeholderAddress\n ];\n // Remove borrower address from market set\n markets[_marketId].verifiedBorrowersForMarket.remove(\n _stakeholderAddress\n );\n\n emit BorrowerRevocation(_marketId, _stakeholderAddress);\n }\n }\n\n /**\n * @notice Checks if a stakeholder has been attested and added to a market.\n * @param _stakeholderAddress Address of the stakeholder to check.\n * @param _attestationRequired Stored boolean indicating if attestation is required for the stakeholder class.\n * @param _stakeholderAttestationIds Mapping of attested Ids for the stakeholder class.\n */\n function _isVerified(\n address _stakeholderAddress,\n bool _attestationRequired,\n mapping(address => bytes32) storage _stakeholderAttestationIds,\n EnumerableSet.AddressSet storage _verifiedStakeholderForMarket\n ) internal view virtual returns (bool isVerified_, bytes32 uuid_) {\n if (_attestationRequired) {\n isVerified_ =\n _verifiedStakeholderForMarket.contains(_stakeholderAddress) &&\n tellerAS.isAttestationActive(\n _stakeholderAttestationIds[_stakeholderAddress]\n );\n uuid_ = _stakeholderAttestationIds[_stakeholderAddress];\n } else {\n isVerified_ = true;\n }\n }\n}\n" + }, + "contracts/MetaForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/metatx/MinimalForwarderUpgradeable.sol\";\n\ncontract MetaForwarder is MinimalForwarderUpgradeable {\n function initialize() external initializer {\n __EIP712_init_unchained(\"TellerMetaForwarder\", \"0.0.1\");\n }\n}\n" + }, + "contracts/mock/aave/AavePoolAddressProviderMock.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPoolAddressesProvider } from \"../../interfaces/aave/IPoolAddressesProvider.sol\";\n\n/**\n * @title PoolAddressesProvider\n * @author Aave\n * @notice Main registry of addresses part of or connected to the protocol, including permissioned roles\n * @dev Acts as factory of proxies and admin of those, so with right to change its implementations\n * @dev Owned by the Aave Governance\n */\ncontract AavePoolAddressProviderMock is Ownable, IPoolAddressesProvider {\n // Identifier of the Aave Market\n string private _marketId;\n\n // Map of registered addresses (identifier => registeredAddress)\n mapping(bytes32 => address) private _addresses;\n\n // Main identifiers\n bytes32 private constant POOL = \"POOL\";\n bytes32 private constant POOL_CONFIGURATOR = \"POOL_CONFIGURATOR\";\n bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\n bytes32 private constant ACL_MANAGER = \"ACL_MANAGER\";\n bytes32 private constant ACL_ADMIN = \"ACL_ADMIN\";\n bytes32 private constant PRICE_ORACLE_SENTINEL = \"PRICE_ORACLE_SENTINEL\";\n bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\n\n /**\n * @dev Constructor.\n * @param marketId The identifier of the market.\n * @param owner The owner address of this contract.\n */\n constructor(string memory marketId, address owner) {\n _setMarketId(marketId);\n transferOwnership(owner);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getMarketId() external view override returns (string memory) {\n return _marketId;\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setMarketId(string memory newMarketId)\n external\n override\n onlyOwner\n {\n _setMarketId(newMarketId);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getAddress(bytes32 id) public view override returns (address) {\n return _addresses[id];\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setAddress(bytes32 id, address newAddress)\n external\n override\n onlyOwner\n {\n address oldAddress = _addresses[id];\n _addresses[id] = newAddress;\n emit AddressSet(id, oldAddress, newAddress);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPool() external view override returns (address) {\n return getAddress(POOL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolConfigurator() external view override returns (address) {\n return getAddress(POOL_CONFIGURATOR);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracle() external view override returns (address) {\n return getAddress(PRICE_ORACLE);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracle(address newPriceOracle)\n external\n override\n onlyOwner\n {\n address oldPriceOracle = _addresses[PRICE_ORACLE];\n _addresses[PRICE_ORACLE] = newPriceOracle;\n emit PriceOracleUpdated(oldPriceOracle, newPriceOracle);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLManager() external view override returns (address) {\n return getAddress(ACL_MANAGER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLManager(address newAclManager) external override onlyOwner {\n address oldAclManager = _addresses[ACL_MANAGER];\n _addresses[ACL_MANAGER] = newAclManager;\n emit ACLManagerUpdated(oldAclManager, newAclManager);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getACLAdmin() external view override returns (address) {\n return getAddress(ACL_ADMIN);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setACLAdmin(address newAclAdmin) external override onlyOwner {\n address oldAclAdmin = _addresses[ACL_ADMIN];\n _addresses[ACL_ADMIN] = newAclAdmin;\n emit ACLAdminUpdated(oldAclAdmin, newAclAdmin);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPriceOracleSentinel() external view override returns (address) {\n return getAddress(PRICE_ORACLE_SENTINEL);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPriceOracleSentinel(address newPriceOracleSentinel)\n external\n override\n onlyOwner\n {\n address oldPriceOracleSentinel = _addresses[PRICE_ORACLE_SENTINEL];\n _addresses[PRICE_ORACLE_SENTINEL] = newPriceOracleSentinel;\n emit PriceOracleSentinelUpdated(\n oldPriceOracleSentinel,\n newPriceOracleSentinel\n );\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function getPoolDataProvider() external view override returns (address) {\n return getAddress(DATA_PROVIDER);\n }\n\n /// @inheritdoc IPoolAddressesProvider\n function setPoolDataProvider(address newDataProvider)\n external\n override\n onlyOwner\n {\n address oldDataProvider = _addresses[DATA_PROVIDER];\n _addresses[DATA_PROVIDER] = newDataProvider;\n emit PoolDataProviderUpdated(oldDataProvider, newDataProvider);\n }\n\n /**\n * @notice Updates the identifier of the Aave market.\n * @param newMarketId The new id of the market\n */\n function _setMarketId(string memory newMarketId) internal {\n string memory oldMarketId = _marketId;\n _marketId = newMarketId;\n emit MarketIdSet(oldMarketId, newMarketId);\n }\n\n //removed for the mock\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external\n {}\n\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl)\n external\n {}\n\n function setPoolImpl(address newPoolImpl) external {}\n}\n" + }, + "contracts/mock/aave/AavePoolMock.sol": { + "content": "pragma solidity ^0.8.0;\n\nimport { IFlashLoanSimpleReceiver } from \"../../interfaces/aave/IFlashLoanSimpleReceiver.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract AavePoolMock {\n bool public flashLoanSimpleWasCalled;\n\n bool public shouldExecuteCallback = true;\n\n function setShouldExecuteCallback(bool shouldExecute) public {\n shouldExecuteCallback = shouldExecute;\n }\n\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external returns (bool success) {\n uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n\n IERC20(asset).transfer(receiverAddress, amount);\n\n uint256 premium = amount / 100;\n address initiator = msg.sender;\n\n if (shouldExecuteCallback) {\n success = IFlashLoanSimpleReceiver(receiverAddress)\n .executeOperation(asset, amount, premium, initiator, params);\n\n require(success == true, \"executeOperation failed\");\n }\n\n IERC20(asset).transferFrom(\n receiverAddress,\n address(this),\n amount + premium\n );\n\n //require balance is what it was plus the fee..\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n\n require(\n balanceAfter >= balanceBefore + premium,\n \"Must repay flash loan\"\n );\n\n flashLoanSimpleWasCalled = true;\n }\n}\n" + }, + "contracts/mock/CollateralManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ICollateralManager.sol\";\n\ncontract CollateralManagerMock is ICollateralManager {\n bool public committedCollateralValid = true;\n bool public deployAndDepositWasCalled;\n\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_) {\n validation_ = committedCollateralValid;\n }\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_) {\n validated_ = true;\n checks_ = new bool[](0);\n }\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 deployAndDepositWasCalled = true;\n }\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 return address(0);\n }\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 */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory collateral_)\n {\n collateral_ = new Collateral[](0);\n }\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount)\n {\n return 500;\n }\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 return true;\n }\n\n function lenderClaimCollateral(uint256 _bidId) external {}\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\n function forceSetCommitCollateralValidation(bool _validation) external {\n committedCollateralValid = _validation;\n }\n}\n" + }, + "contracts/mock/LenderCommitmentForwarderMock.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\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentForwarderMock is\n ILenderCommitmentForwarder,\n ITellerV2MarketForwarder\n{\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n bool public submitBidWithCollateralWasCalled;\n bool public acceptBidWasCalled;\n bool public submitBidWasCalled;\n bool public acceptCommitmentWithRecipientWasCalled;\n bool public acceptCommitmentWithRecipientAndProofWasCalled;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n constructor() {}\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256) {}\n\n function setCommitment(uint256 _commitmentId, Commitment memory _commitment)\n public\n {\n commitments[_commitmentId] = _commitment;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n public\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n public\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n /* function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type)\n public\n returns (CollateralType)\n {\n return super._getEscrowCollateralType(_type);\n }\n\n function validateCommitmentSuper(uint256 _commitmentId) public {\n super.validateCommitment(commitments[_commitmentId]);\n }*/\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 acceptCommitmentWithRecipientWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\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 ) public returns (uint256 bidId) {\n acceptCommitmentWithRecipientAndProofWasCalled = true;\n\n Commitment storage commitment = commitments[_commitmentId];\n\n address lendingToken = commitment.principalTokenAddress;\n\n _mockAcceptCommitmentTokenTransfer(\n lendingToken,\n _principalAmount,\n _recipient\n );\n }\n\n function _mockAcceptCommitmentTokenTransfer(\n address lendingToken,\n uint256 principalAmount,\n address _recipient\n ) internal {\n IERC20(lendingToken).transfer(_recipient, principalAmount);\n }\n\n /*\n Override methods \n */\n\n /* function _submitBid(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWasCalled = true;\n return 1;\n }\n\n function _submitBidWithCollateral(CreateLoanArgs memory, address)\n internal\n override\n returns (uint256 bidId)\n {\n submitBidWithCollateralWasCalled = true;\n return 1;\n }\n\n function _acceptBid(uint256, address) internal override returns (bool) {\n acceptBidWasCalled = true;\n\n return true;\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/LenderManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/ILenderManager.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\n\ncontract LenderManagerMock is ILenderManager, ERC721Upgradeable {\n //bidId => lender\n mapping(uint256 => address) public registeredLoan;\n\n constructor() {}\n\n function registerLoan(uint256 _bidId, address _newLender)\n external\n override\n {\n registeredLoan[_bidId] = _newLender;\n }\n\n function ownerOf(uint256 _bidId)\n public\n view\n override(ERC721Upgradeable, IERC721Upgradeable)\n returns (address)\n {\n return registeredLoan[_bidId];\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/mock/MockHypernativeOracle.sol": { + "content": "\nimport \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\ncontract MockHypernativeOracle is IHypernativeOracle {\n mapping(address => bool) private blacklistedAccounts;\n mapping(address => bool) private blacklistedContexts;\n mapping(address => bool) private timeExceeded;\n\n function setBlacklistedAccount(address account, bool status) external {\n blacklistedAccounts[account] = status;\n }\n\n function setBlacklistedContext(address context, bool status) external {\n blacklistedContexts[context] = status;\n }\n\n function setTimeExceeded(address account, bool status) external {\n timeExceeded[account] = status;\n }\n\n function isBlacklistedAccount(address account) external view override returns (bool) {\n return blacklistedAccounts[account];\n }\n\n function isBlacklistedContext(address origin, address sender) external view override returns (bool) {\n return blacklistedContexts[origin];\n }\n\n function isTimeExceeded(address account) external view override returns (bool) {\n return timeExceeded[account];\n }\n\n function register(address account) external override {}\n\n function registerStrict(address account) external override {}\n}\n" + }, + "contracts/mock/MockPriceAdapter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../interfaces/IPriceAdapter.sol\";\n\ncontract MockPriceAdapter is IPriceAdapter {\n uint256 public mockPriceRatioQ96;\n mapping(bytes32 => bytes) public priceRoutes;\n\n function setMockPriceRatioQ96(uint256 _price) external {\n mockPriceRatioQ96 = _price;\n }\n\n function registerPriceRoute(bytes memory route) external returns (bytes32) {\n bytes32 routeHash = keccak256(route);\n priceRoutes[routeHash] = route;\n return routeHash;\n }\n\n function getPriceRatioQ96(bytes32 route) external view returns (uint256) {\n require(priceRoutes[route].length > 0, \"Route not found\");\n return mockPriceRatioQ96;\n }\n}\n" + }, + "contracts/mock/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/mock/ReputationManagerMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IReputationManager.sol\";\n\ncontract ReputationManagerMock is IReputationManager {\n constructor() {}\n\n function initialize(address protocolAddress) external override {}\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory _loanIds)\n {}\n\n function updateAccountReputation(address _account) external {}\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark)\n {\n return RepMark.Good;\n }\n}\n" + }, + "contracts/mock/SwapRolloverLoanMock.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\ncontract MockSwapRolloverLoan 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\n \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 _verifyFlashCallback( \n flashSwapArgs.token0,\n flashSwapArgs.token1,\n flashSwapArgs.fee,\n msg.sender \n );\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 Verify the flash callback with a remote call to the factory \n @dev This allows better compatibility with factories that have different 'init hashes' such as forks like sushi \n @dev Originally used CallbackValidation.verifyCallback which computed locally but was not as cross compatible \n */\n function _verifyFlashCallback( \n address token0,\n address token1,\n uint24 fee,\n address _msgSender \n ) internal virtual {\n\n address poolAddress = IUniswapV3Factory( factory )\n .getPool( token0, token1, fee );\n\n require( _msgSender == poolAddress );\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/mock/TellerASMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport \"../EAS/TellerASEIP712Verifier.sol\";\nimport \"../EAS/TellerASRegistry.sol\";\n\nimport \"../interfaces/IASRegistry.sol\";\nimport \"../interfaces/IEASEIP712Verifier.sol\";\n\ncontract TellerASMock is TellerAS {\n constructor()\n TellerAS(\n IASRegistry(new TellerASRegistry()),\n IEASEIP712Verifier(new TellerASEIP712Verifier())\n )\n {}\n\n function isAttestationActive(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n" + }, + "contracts/mock/TellerV2SolMock.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"../TellerV2.sol\";\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../TellerV2Context.sol\";\nimport \"../pausing/HasProtocolPausingManager.sol\";\nimport { Collateral } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\nimport { LoanDetails, Payment, BidState } from \"../TellerV2Storage.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../interfaces/ILoanRepaymentCallbacks.sol\";\n\n\n/*\nThis is only used for sol test so its named specifically to avoid being used for the typescript tests.\n*/\ncontract TellerV2SolMock is \nITellerV2,\nIProtocolFee, \nTellerV2Storage , \nHasProtocolPausingManager,\nILoanRepaymentCallbacks\n{\n uint256 public amountOwedMockPrincipal;\n uint256 public amountOwedMockInterest;\n address public approvedForwarder;\n bool public isPausedMock;\n\n address public mockOwner;\n address public mockProtocolFeeRecipient;\n\n mapping(address => bool) public mockPausers;\n\n\n PaymentCycleType globalBidPaymentCycleType = PaymentCycleType.Seconds;\n uint32 globalBidPaymentCycleDuration = 3000;\n\n uint256 mockLoanDefaultTimestamp;\n bool public lenderCloseLoanWasCalled;\n\n function setMarketRegistry(address _marketRegistry) public {\n marketRegistry = IMarketRegistry(_marketRegistry);\n }\n\n function setProtocolPausingManager(address _protocolPausingManager) public {\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n function getMarketRegistry() external view returns (IMarketRegistry) {\n return marketRegistry;\n }\n\n function protocolFee() external view returns (uint16) {\n return 100;\n }\n\n\n function getEscrowVault() external view returns(address){\n return address(0);\n }\n\n\n function paused() external view returns(bool){\n return isPausedMock;\n }\n\n\n function setMockOwner(address _newOwner) external {\n mockOwner = _newOwner;\n }\n function owner() external view returns(address){\n return mockOwner;\n }\n \n\n \n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n approvedForwarder = _forwarder;\n }\n\n\n function submitBid(\n address _lendingToken,\n uint256 _marketId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata,\n address _receiver\n ) public returns (uint256 bidId_) {\n \n\n\n bidId_ = bidId;\n\n Bid storage bid = bids[bidId_];\n bid.borrower = msg.sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n /*(bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketId);*/\n\n bid.terms.APR = _APR;\n\n bidId++; //nextBidId\n\n }\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 ) public returns (uint256 bidId_) {\n return submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\n\n function lenderCloseLoan(uint256 _bidId) external {\n lenderCloseLoanWasCalled = true;\n }\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external\n {\n lenderCloseLoanWasCalled = true;\n }\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256)\n {\n return mockLoanDefaultTimestamp;\n }\n\n function liquidateLoanFull(uint256 _bidId) external {}\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external\n {}\n\n function repayLoanMinimum(uint256 _bidId) external {}\n\n function repayLoanFull(uint256 _bidId) external {\n Bid storage bid = bids[_bidId];\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n uint256 _amount = owedPrincipal + interest;\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n function repayLoan(uint256 _bidId, uint256 _amount) public {\n Bid storage bid = bids[_bidId];\n\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n msg.sender,\n address(this),\n _amount\n );\n }\n\n \n\n /*\n * @notice Calculates the minimum payment amount due for a loan.\n * @param _bidId The id of the loan bid to get the payment amount for.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n if (bids[_bidId].state != BidState.ACCEPTED) return due;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = owedPrincipal;\n due.interest = interest;\n }\n\n function lenderAcceptBid(uint256 _bidId)\n public\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n Bid storage bid = bids[_bidId];\n\n bid.lender = msg.sender;\n\n bid.state = BidState.ACCEPTED;\n\n //send tokens to caller\n IERC20(bid.loanDetails.lendingToken).transferFrom(\n bid.lender,\n bid.receiver,\n bid.loanDetails.principal\n );\n //for the reciever\n\n return (0, bid.loanDetails.principal, 0);\n }\n\n function getBidState(uint256 _bidId)\n public\n view\n virtual\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getLoanDetails(uint256 _bidId)\n public\n view\n returns (LoanDetails memory)\n {\n return bids[_bidId].loanDetails;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n public\n view\n returns (uint256[] memory)\n {}\n\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n virtual\n returns (bool)\n {}\n\n function isPaymentLate(uint256 _bidId) public view returns (bool) {}\n\n function getLoanBorrower(uint256 _bidId)\n external\n view\n virtual\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n function getLoanLender(uint256 _bidId)\n external\n view\n virtual\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = bid.lender;\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = bid.loanDetails.lastRepaidTimestamp;\n bidState = bid.state;\n }\n\n function setLastRepaidTimestamp(uint256 _bidId, uint32 _timestamp) public {\n bids[_bidId].loanDetails.lastRepaidTimestamp = _timestamp;\n }\n\n\n\n function mock_setLoanDefaultTimestamp(\n uint256 _defaultedAt\n ) external returns (uint256){\n mockLoanDefaultTimestamp = _defaultedAt;\n } \n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n public\n view\n returns (address)\n {}\n\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n public\n {}\n\n\n function getProtocolFeeRecipient () public view returns(address){\n return mockProtocolFeeRecipient;\n }\n\n function setMockProtocolFeeRecipient(address _address) public {\n mockProtocolFeeRecipient = _address;\n }\n\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleTypeForTerms(bidTermsId);\n }*/\n\n return globalBidPaymentCycleType;\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n /* bytes32 bidTermsId = bidMarketTermsId[_bidId];\n if (bidTermsId != bytes32(0)) {\n return marketRegistry.getPaymentCycleDurationForTerms(bidTermsId);\n }*/\n\n Bid storage bid = bids[_bidId];\n\n return globalBidPaymentCycleDuration;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3FactoryMock.sol": { + "content": "contract UniswapV3FactoryMock {\n address poolMock;\n\n function getPool(address token0, address token1, uint24 fee)\n public\n returns (address)\n {\n return poolMock;\n }\n\n function setPoolMock(address _pool) public {\n poolMock = _pool;\n }\n}\n" + }, + "contracts/mock/uniswap/UniswapV3PoolMock.sol": { + "content": "\n \n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol\";\n\ncontract UniswapV3PoolMock {\n //this represents an equal price ratio\n uint160 mockSqrtPriceX96 = 2 ** 96;\n\n address mockToken0;\n address mockToken1;\n uint24 fee;\n\n \n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n\n function set_mockSqrtPriceX96(uint160 _price) public {\n mockSqrtPriceX96 = _price;\n }\n\n function set_mockToken0(address t0) public {\n mockToken0 = t0;\n }\n\n\n function set_mockToken1(address t1) public {\n mockToken1 = t1;\n }\n\n function set_mockFee(uint24 f0) public {\n fee = f0;\n }\n\n function token0() public returns (address) {\n return mockToken0;\n }\n\n function token1() public returns (address) {\n return mockToken1;\n }\n\n\n function slot0() public returns (Slot0 memory slot0) {\n return\n Slot0({\n sqrtPriceX96: mockSqrtPriceX96,\n tick: 0,\n observationIndex: 0,\n observationCardinality: 0,\n observationCardinalityNext: 0,\n feeProtocol: 0,\n unlocked: true\n });\n }\n\n //mock fn \n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n // Initialize the return arrays\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n\n // Mock data generation - replace this with your logic or static values\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n // Generate mock data. Here we're just using simple static values for demonstration.\n // You should replace these with dynamic values based on your testing needs.\n tickCumulatives[i] = int56(1000 * int256(i)); // Example mock data\n secondsPerLiquidityCumulativeX128s[i] = uint160(2000 * i); // Example mock data\n }\n\n return (tickCumulatives, secondsPerLiquidityCumulativeX128s);\n }\n\n\n\n\n /* \n\n interface IUniswapV3FlashCallback {\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n }\n */\n event Flash(address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);\n\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uint256 balance0Before = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1Before = IERC20(mockToken1).balanceOf(address(this));\n \n\n if (amount0 > 0) {\n IERC20(mockToken0).transfer(recipient, amount0);\n }\n if (amount1 > 0) {\n IERC20(mockToken1).transfer(recipient, amount1);\n }\n\n // Execute the callback\n IUniswapV3FlashCallback(recipient).uniswapV3FlashCallback( // what will the fee actually be irl ? \n amount0 / 100, // Simulated fee for token0 (1%)\n amount1 / 100, // Simulated fee for token1 (1%)\n data\n );\n\n uint256 balance0After = IERC20(mockToken0).balanceOf(address(this));\n uint256 balance1After = IERC20(mockToken1).balanceOf(address(this));\n\n \n\n require(balance0After >= balance0Before + (amount0 / 100), \"Insufficient repayment for token0\");\n require(balance1After >= balance1Before + (amount1 / 100), \"Insufficient repayment for token1\");\n\n emit Flash(recipient, amount0, amount1, balance0After - balance0Before, balance1After - balance1Before);\n }\n \n \n\n}\n\n\n\n\n\n\n\n\n " + }, + "contracts/mock/uniswap/UniswapV3QuoterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\ncontract UniswapV3QuoterMock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external view\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3QuoterV2Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/IQuoterV2.sol';\n\ncontract UniswapV3QuoterV2Mock {\n \n function quoteExactInput(bytes memory path, uint256 amountIn)\n external\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n ) {\n\n // mock for now \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3Router02Mock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter02.sol';\n\ncontract UniswapV3Router02Mock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n \n function exactInput(\n ISwapRouter02.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/uniswap/UniswapV3RouterMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\ncontract UniswapV3RouterMock {\n event SwapExecuted(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);\n\n function exactInputSingle(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOutMinimum,\n address recipient\n ) external {\n require(IERC20(tokenIn).balanceOf(msg.sender) >= amountIn, \"Insufficient balance for swap\");\n require(IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn), \"Transfer failed\");\n\n // Mock behavior: transfer the output token to the recipient\n uint256 amountOut = amountIn; // Mocking 1:1 swap for simplicity\n require(amountOut >= amountOutMinimum, \"Output amount too low\");\n\n IERC20(tokenOut).transfer(recipient, amountOut);\n emit SwapExecuted(tokenIn, tokenOut, amountIn, amountOut);\n }\n\n\n function exactInput(\n ISwapRouter.ExactInputParams memory swapParams \n ) external payable returns (uint256 amountOut) {\n // decodes the path and performs the swaps \n }\n\n}" + }, + "contracts/mock/UniswapPricingHelperMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelperMock\n{\n\n\n // use uniswap exp helper instead ? \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 return STANDARD_EXPANSION_FACTOR; \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 /**\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). Taken directly from uniswap oracle lib \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/mock/WethMock.sol": { + "content": "/**\n *Submitted for verification at Etherscan.io on 2017-12-12\n */\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\ncontract WethMock {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint256 wad);\n event Transfer(address indexed src, address indexed dst, uint256 wad);\n event Deposit(address indexed dst, uint256 wad);\n event Withdrawal(address indexed src, uint256 wad);\n\n mapping(address => uint256) public balanceOf;\n mapping(address => mapping(address => uint256)) public allowance;\n\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n payable(msg.sender).transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint256) {\n return address(this).balance;\n }\n\n function approve(address guy, uint256 wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint256 wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint256 wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad, \"insufficient balance\");\n\n if (src != msg.sender) {\n require(\n allowance[src][msg.sender] >= wad,\n \"insufficient allowance\"\n );\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n\n\n \n}\n" + }, + "contracts/openzeppelin/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {UpgradeableBeacon} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\npragma solidity ^0.8.0;\n\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n constructor(address implementation, bytes memory _data) payable {\n ERC1967Utils.upgradeToAndCall(implementation, _data);\n }\n\n /**\n * @dev Returns the current implementation address.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _implementation() internal view virtual override returns (address) {\n return ERC1967Utils.getImplementation();\n }\n}" + }, + "contracts/openzeppelin/ERC1967/ERC1967Utils.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\npragma solidity ^0.8.0;\n\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../utils/Address.sol\";\nimport {StorageSlot} from \"../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev The `implementation` of the proxy is invalid.\n */\n error ERC1967InvalidImplementation(address implementation);\n\n /**\n * @dev The `admin` of the proxy is invalid.\n */\n error ERC1967InvalidAdmin(address admin);\n\n /**\n * @dev The `beacon` of the proxy is invalid.\n */\n error ERC1967InvalidBeacon(address beacon);\n\n /**\n * @dev An upgrade function sees `msg.value > 0` that may be lost.\n */\n error ERC1967NonPayable();\n\n /**\n * @dev Returns the current implementation address.\n */\n function getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n if (newImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(newImplementation);\n }\n StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n\n if (data.length > 0) {\n Address.functionDelegateCall(newImplementation, data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the ERC-1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n if (newAdmin == address(0)) {\n revert ERC1967InvalidAdmin(address(0));\n }\n StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {IERC1967-AdminChanged} event.\n */\n function changeAdmin(address newAdmin) internal {\n emit AdminChanged(getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the ERC-1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n if (newBeacon.code.length == 0) {\n revert ERC1967InvalidBeacon(newBeacon);\n }\n\n StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n address beaconImplementation = IBeacon(newBeacon).implementation();\n if (beaconImplementation.code.length == 0) {\n revert ERC1967InvalidImplementation(beaconImplementation);\n }\n }\n\n /**\n * @dev Change the beacon and trigger a setup call if data is nonempty.\n * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n * to avoid stuck value in the contract.\n *\n * Emits an {IERC1967-BeaconUpgraded} event.\n *\n * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n * efficiency.\n */\n function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n\n if (data.length > 0) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n } else {\n _checkNonPayable();\n }\n }\n\n /**\n * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n * if an upgrade doesn't perform an initialization call.\n */\n function _checkNonPayable() private {\n if (msg.value > 0) {\n revert ERC1967NonPayable();\n }\n }\n}" + }, + "contracts/openzeppelin/ERC1967/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}" + }, + "contracts/openzeppelin/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\npragma solidity ^0.8.0;\n\n\nimport {Context} from \"./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 * The initial owner is set to the address provided by the deployer. This can\n * 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 /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\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 if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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 if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\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}" + }, + "contracts/openzeppelin/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\npragma solidity ^0.8.0;\n\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n * function and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n}" + }, + "contracts/openzeppelin/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n * during an upgrade.\n */\n string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n /**\n * @dev Sets the initial owner who can perform upgrades.\n */\n constructor(address initialOwner) Ownable(initialOwner) {}\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n * - If `data` is empty, `msg.value` must be zero.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}" + }, + "contracts/openzeppelin/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n//import {IERC20} from \"../IERC20.sol\";\n//import {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 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 /**\n * @dev An operation with an ERC-20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n *\n * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n *\n * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n * set here.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n \n \n \n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n // bubble errors\n if iszero(success) {\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n\n if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly { // (\"memory-safe\")\n success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0)\n }\n return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n }\n}" + }, + "contracts/openzeppelin/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport {ERC1967Utils} from \"./ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"./ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"./ERC1967/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot\n * is generally fine if the implementation is trusted.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n // An immutable address for the admin to avoid unnecessary SLOADs before each call\n // at the expense of removing the ability to change the admin once it's set.\n // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n // with its own ability to transfer the permissions to another account.\n address private immutable _admin;\n\n /**\n * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n */\n error ProxyDeniedAdminAccess();\n\n /**\n * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n * {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _admin = address(new ProxyAdmin(initialOwner));\n // Set the storage value and emit an event for ERC-1967 compatibility\n ERC1967Utils.changeAdmin(_proxyAdmin());\n }\n\n /**\n * @dev Returns the admin of this proxy.\n */\n function _proxyAdmin() internal view virtual returns (address) {\n return _admin;\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n */\n function _fallback() internal virtual override {\n if (msg.sender == _proxyAdmin()) {\n if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n revert ProxyDeniedAdminAccess();\n } else {\n _dispatchUpgradeToAndCall();\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - If `data` is empty, `msg.value` must be zero.\n */\n function _dispatchUpgradeToAndCall() private {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n ERC1967Utils.upgradeToAndCall(newImplementation, data);\n }\n}" + }, + "contracts/openzeppelin/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\npragma solidity ^0.8.0;\n\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert Errors.InsufficientBalance(address(this).balance, amount);\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert Errors.FailedCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {Errors.FailedCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert Errors.InsufficientBalance(address(this).balance, value);\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n * of an unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {Errors.FailedCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n */\n function _revert(bytes memory returndata) 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 Errors.FailedCall();\n }\n }\n}" + }, + "contracts/openzeppelin/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\npragma solidity ^0.8.0;\n\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}" + }, + "contracts/openzeppelin/utils/Errors.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n */\nlibrary Errors {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error InsufficientBalance(uint256 balance, uint256 needed);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedCall();\n\n /**\n * @dev The deployment failed.\n */\n error FailedDeployment();\n}" + }, + "contracts/openzeppelin/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(newImplementation.code.length > 0);\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}" + }, + "contracts/oracleprotection/HypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\n\ncontract HypernativeOracle is AccessControl {\n struct OracleRecord {\n uint256 registrationTime;\n bool isPotentialRisk;\n }\n\n bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n bytes32 public constant CONSUMER_ROLE = keccak256(\"CONSUMER_ROLE\");\n uint256 internal threshold = 2 minutes;\n\n mapping(bytes32 /*hashedAccount*/ => OracleRecord) internal accountHashToRecord;\n \n event ConsumerAdded(address consumer);\n event ConsumerRemoved(address consumer);\n event Registered(address consumer, address account);\n event Whitelisted(bytes32[] hashedAccounts);\n event Allowed(bytes32[] hashedAccounts);\n event Blacklisted(bytes32[] hashedAccounts);\n event TimeThresholdChanged(uint256 threshold);\n\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Hypernative Oracle error: admin required\");\n _;\n }\n\n modifier onlyOperator() {\n require(hasRole(OPERATOR_ROLE, msg.sender), \"Hypernative Oracle error: operator required\");\n _;\n }\n\n modifier onlyConsumer {\n require(hasRole(CONSUMER_ROLE, msg.sender), \"Hypernative Oracle error: consumer required\");\n _;\n }\n\n constructor(address _admin) {\n _grantRole(DEFAULT_ADMIN_ROLE, _admin);\n }\n\n function register(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n emit Registered(msg.sender, _account);\n }\n\n function registerStrict(address _account) external onlyConsumer() {\n bytes32 _hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n require(accountHashToRecord[_hashedAccount].registrationTime == 0, \"Account already registered\");\n accountHashToRecord[_hashedAccount].registrationTime = block.timestamp;\n accountHashToRecord[_hashedAccount].isPotentialRisk = true;\n emit Registered(msg.sender, _account);\n }\n\n // **\n // * @dev Operator only function, can be used to whitelist accounts in order to pre-approve them\n // * @param hashedAccounts array of hashed accounts\n // */\n function whitelist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].registrationTime = 1;\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Whitelisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, can be used to blacklist accounts in order to prevent them from interacting with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function blacklist(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = true;\n }\n emit Blacklisted(hashedAccounts);\n }\n\n // **\n // * @dev Operator only function, when strict mode is being used, this function can be used to allow accounts to interact with the protocol\n // * @param hashedAccounts array of hashed accounts\n // */\n function allow(bytes32[] calldata hashedAccounts) public onlyOperator() {\n for (uint256 i; i < hashedAccounts.length; i++) {\n accountHashToRecord[hashedAccounts[i]].isPotentialRisk = false;\n }\n emit Allowed(hashedAccounts);\n }\n\n /**\n * @dev Admin only function, can be used to block any interaction with the protocol, meassured in seconds\n */\n function changeTimeThreshold(uint256 _newThreshold) public onlyAdmin() {\n require(_newThreshold >= 2 minutes, \"Threshold must be greater than 2 minutes\");\n threshold = _newThreshold;\n emit TimeThresholdChanged(threshold);\n }\n\n function addConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _grantRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerAdded(consumers[i]);\n }\n }\n\n function revokeConsumers(address[] memory consumers) public onlyAdmin() {\n for (uint256 i; i < consumers.length; i++) {\n _revokeRole(CONSUMER_ROLE, consumers[i]);\n emit ConsumerRemoved(consumers[i]);\n }\n }\n\n function addOperator(address operator) public onlyAdmin() {\n _grantRole(OPERATOR_ROLE, operator);\n }\n\n function revokeOperator(address operator) public onlyAdmin() {\n _revokeRole(OPERATOR_ROLE, operator);\n }\n\n function changeAdmin(address _newAdmin) public onlyAdmin() {\n _grantRole(DEFAULT_ADMIN_ROLE, _newAdmin);\n _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n\n //if true, the account has been registered for two minutes \n function isTimeExceeded(address account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(account, address(this)));\n require(accountHashToRecord[hashedAccount].registrationTime != 0, \"Account not registered\");\n return block.timestamp - accountHashToRecord[hashedAccount].registrationTime > threshold;\n }\n\n function isBlacklistedContext(address _origin, address _sender) external onlyConsumer() view returns (bool) {\n bytes32 hashedOrigin = keccak256(abi.encodePacked(_origin, address(this)));\n bytes32 hashedSender = keccak256(abi.encodePacked(_sender, address(this)));\n return accountHashToRecord[hashedOrigin].isPotentialRisk || accountHashToRecord[hashedSender].isPotentialRisk;\n }\n\n function isBlacklistedAccount(address _account) external onlyConsumer() view returns (bool) {\n bytes32 hashedAccount = keccak256(abi.encodePacked(_account, address(this)));\n return accountHashToRecord[hashedAccount].isPotentialRisk;\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 ) , \"O_NA\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"O_NA\");\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 && msg.sender.code.length != 0 && !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/pausing/HasProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n \n\nabstract contract HasProtocolPausingManager \n is \n IHasProtocolPausingManager \n {\n \n\n //Both this bool and the address together take one storage slot \n bool private __paused;// Deprecated. handled by pausing manager now\n\n address private _protocolPausingManager; // 20 bytes, gap will start at new slot \n \n\n modifier whenLiquidationsNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). liquidationsPaused(), \"Liquidations paused\" );\n \n _;\n }\n\n \n modifier whenProtocolNotPaused() {\n require(! IProtocolPausingManager(_protocolPausingManager). protocolPaused(), \"Protocol paused\" );\n \n _;\n }\n \n\n \n function _setProtocolPausingManager(address protocolPausingManager) internal {\n _protocolPausingManager = protocolPausingManager ;\n }\n\n\n function getProtocolPausingManager() public view returns (address){\n\n return _protocolPausingManager;\n }\n\n \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[49] private __gap;\n}\n" + }, + "contracts/pausing/ProtocolPausingManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\n \ncontract ProtocolPausingManager is ContextUpgradeable, OwnableUpgradeable, IProtocolPausingManager , IPausableTimestamp{\n using MathUpgradeable for uint256;\n\n bool private _protocolPaused; \n bool private _liquidationsPaused; \n\n mapping(address => bool) public pauserRoleBearer;\n\n\n uint256 private lastPausedAt;\n uint256 private lastUnpausedAt;\n\n\n // Events\n event PausedProtocol(address indexed account);\n event UnpausedProtocol(address indexed account);\n event PausedLiquidations(address indexed account);\n event UnpausedLiquidations(address indexed account);\n event PauserAdded(address indexed account);\n event PauserRemoved(address indexed account);\n \n \n modifier onlyPauser() {\n require( isPauser( _msgSender()) );\n _;\n }\n\n\n //need to initialize so owner is owner (transfer ownership to safe)\n function initialize(\n \n ) external initializer {\n\n __Ownable_init();\n\n }\n \n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function protocolPaused() public view virtual returns (bool) {\n return _protocolPaused;\n }\n\n\n function liquidationsPaused() public view virtual returns (bool) {\n return _liquidationsPaused;\n }\n\n \n\n\n function pauseProtocol() public virtual onlyPauser {\n require( _protocolPaused == false);\n _protocolPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedProtocol(_msgSender());\n }\n\n \n function unpauseProtocol() public virtual onlyPauser {\n \n require( _protocolPaused == true);\n _protocolPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedProtocol(_msgSender());\n }\n\n function pauseLiquidations() public virtual onlyPauser {\n \n require( _liquidationsPaused == false);\n _liquidationsPaused = true;\n lastPausedAt = block.timestamp;\n emit PausedLiquidations(_msgSender());\n }\n\n \n function unpauseLiquidations() public virtual onlyPauser {\n require( _liquidationsPaused == true);\n _liquidationsPaused = false;\n lastUnpausedAt = block.timestamp;\n emit UnpausedLiquidations(_msgSender());\n }\n\n function getLastPausedAt() \n external view \n returns (uint256) {\n\n return lastPausedAt;\n\n } \n\n\n function getLastUnpausedAt() \n external view \n returns (uint256) {\n\n return lastUnpausedAt;\n\n } \n\n\n\n\n // Role Management \n\n function addPauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = true;\n emit PauserAdded(_pauser);\n }\n\n\n function removePauser(address _pauser) public virtual onlyOwner {\n pauserRoleBearer[_pauser] = false;\n emit PauserRemoved(_pauser);\n }\n\n\n function isPauser(address _account) public view returns(bool){\n return pauserRoleBearer[_account] || _account == owner();\n }\n\n \n}\n" + }, + "contracts/penetrationtesting/LenderGroupMockInteract.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \nimport \"../interfaces/ILenderCommitmentGroup.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n \n import \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n \ncontract LenderGroupMockInteract {\n \n \n \n function addPrincipalToCommitmentGroup( \n address _target,\n address _principalToken,\n address _sharesToken,\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut ) public {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), _amount);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, _amount);\n\n\n //need to suck in ERC 20 and approve them ? \n\n uint256 sharesAmount = ILenderCommitmentGroup(_target).addPrincipalToCommitmentGroup(\n _amount,\n _sharesRecipient,\n _minSharesAmountOut \n\n );\n\n \n IERC20(_sharesToken).transfer(msg.sender, sharesAmount);\n }\n\n /**\n * @notice Allows the contract owner to prepare shares for withdrawal in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to prepare for withdrawal.\n */\n function prepareSharesForBurn(\n address _target,\n uint256 _amountPoolSharesTokens\n ) external {\n ILenderCommitmentGroup(_target).prepareSharesForBurn(\n _amountPoolSharesTokens\n );\n }\n\n /**\n * @notice Allows the contract owner to burn shares and withdraw principal tokens from the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _amountPoolSharesTokens The amount of share tokens to burn.\n * @param _recipient The address to receive the withdrawn principal tokens.\n * @param _minAmountOut The minimum amount of principal tokens expected from the withdrawal.\n */\n function burnSharesToWithdrawEarnings(\n address _target,\n address _principalToken,\n address _poolSharesToken,\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external {\n\n\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_poolSharesToken).transferFrom(msg.sender, address(this), _amountPoolSharesTokens);\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_poolSharesToken).approve(_target, _amountPoolSharesTokens);\n\n\n\n uint256 amountOut = ILenderCommitmentGroup(_target).burnSharesToWithdrawEarnings(\n _amountPoolSharesTokens,\n _recipient,\n _minAmountOut\n );\n\n IERC20(_principalToken).transfer(msg.sender, amountOut);\n }\n\n /**\n * @notice Allows the contract owner to liquidate a defaulted loan with incentive in the specified LenderCommitmentGroup contract.\n * @param _target The LenderCommitmentGroup contract address.\n * @param _bidId The ID of the defaulted loan bid to liquidate.\n * @param _tokenAmountDifference The incentive amount required for liquidation.\n */\n function liquidateDefaultedLoanWithIncentive(\n address _target,\n address _principalToken,\n uint256 _bidId,\n int256 _tokenAmountDifference,\n int256 loanAmount \n ) external {\n\n // Transfer the ERC20 tokens to this contract\n IERC20(_principalToken).transferFrom(msg.sender, address(this), uint256(_tokenAmountDifference + loanAmount));\n\n // Approve the target contract to spend tokens on behalf of this contract\n IERC20(_principalToken).approve(_target, uint256(_tokenAmountDifference + loanAmount));\n \n\n ILenderCommitmentGroup(_target).liquidateDefaultedLoanWithIncentive(\n _bidId,\n _tokenAmountDifference\n );\n }\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAerodrome.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAerodromePool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n import {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n\n\ncontract PriceAdapterAerodrome is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n // hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n // store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address poolAddress, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n uint256 latestObservationTick = IAerodromePool(poolAddress).observationLength() -1; \n\n\n if (twapInterval == 0 ){\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative, uint256 reserve1Cumulative) =\n IAerodromePool(poolAddress).observations( latestObservationTick -1 );\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative ) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative ) / latestObservationTick;\n\n return getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ; \n }\n\n\n \n // Get two observations: current and one from twapInterval seconds ago\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = 0; // current\n secondsAgos[1] = twapInterval + 0 ; // oldest\n \n\n // Fetch observations\n \n\n (uint256 timestamp0, uint256 reserve0Cumulative0, uint256 reserve1Cumulative0) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[0]);\n\n (uint256 timestamp1, uint256 reserve0Cumulative1, uint256 reserve1Cumulative1) =\n IAerodromePool(poolAddress).observations(latestObservationTick - secondsAgos[1]);\n\n // Calculate time-weighted average reserves\n uint256 timeElapsed = timestamp0 - timestamp1 ;\n require(timeElapsed > 0, \"Invalid time elapsed\");\n\n // Average reserves over the interval -- divisor isnt exactly right ? \n uint256 avgReserve0 = (reserve0Cumulative0 - reserve0Cumulative1) / latestObservationTick;\n uint256 avgReserve1 = (reserve1Cumulative0 - reserve1Cumulative1) / latestObservationTick;\n \n \n // To avoid precision loss, calculate: sqrt(reserve1) / sqrt(reserve0) * 2^96 \n sqrtPriceX96 = getSqrtPriceQ96FromReserves ( avgReserve0, avgReserve1 ) ;\n\n\n\n\n }\n\n\n\n function getSqrtPriceQ96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n\n }\n\n\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterAlgebra.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/defi/IAlgebraPool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n Price adapter for Algebra V1 pools (Camelot V3 on ApeChain).\n Uses globalState() instead of slot0() and getTimepoints() instead of observe().\n\n*/\n\ncontract PriceAdapterAlgebra is IPriceAdapter {\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n }\n\n mapping(bytes32 => bytes) public priceRoutes;\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n\n /* External Functions */\n\n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n require( route_array.length ==1 || route_array.length ==2, \"invalid route length\" );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getAlgebraPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n // -------\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n // -------\n\n function getAlgebraPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address algebraPool, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n if (twapInterval == 0) {\n // return the current price from globalState (Algebra equivalent of slot0)\n (sqrtPriceX96, , , , , , , ) = IAlgebraPool(algebraPool).globalState();\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, ) = IAlgebraPool(algebraPool)\n .getTimepoints(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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV2Pair.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {FixedPointMathLib} from \"../libraries/erc4626/utils/FixedPointMathLib.sol\";\n\n/*\n\n UniswapV2 Price Adapter (compatible with Sushiswap and other V2 forks)\n Uses reserves for current price \n\n\n Cannot compute TWAP price as uniswapV2 doesnt provide historic data \n\n*/\n\n\ncontract PriceAdapterUniswapV2 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // Get sqrtPriceX96 from UniswapV2 reserves\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(address uniswapV2Pool, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pool);\n\n if (twapInterval == 0) {\n // Use current reserves for immediate price\n (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();\n sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1));\n } else {\n // For TWAP, use cumulative prices\n // Note: In a single transaction, we can only get the current cumulative prices\n // This requires storing historical cumulative prices on-chain for proper TWAP calculation\n // For now, we use current reserves as a fallback\n (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();\n sqrtPriceX96 = getSqrtPriceX96FromReserves(uint256(reserve0), uint256(reserve1));\n }\n }\n\n function getSqrtPriceX96FromReserves(uint256 reserve0, uint256 reserve1)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n // Calculate sqrt(reserve1 / reserve0) * 2^96\n // This represents the price of token0 in terms of token1\n\n require(reserve0 > 0, \"Reserve0 cannot be zero\");\n require(reserve1 > 0, \"Reserve1 cannot be zero\");\n\n uint256 sqrtReserve0 = FixedPointMathLib.sqrt(reserve0);\n uint256 sqrtReserve1 = FixedPointMathLib.sqrt(reserve1);\n\n sqrtPriceX96 = uint160(\n FullMath.mulDiv(sqrtReserve1, FixedPointQ96.Q96, sqrtReserve0)\n );\n }\n\n function getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\n\nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\n/*\n\n This is (typically) compatible with Sushiswap and Aerodrome \n\n*/\n\n\ncontract PriceAdapterUniswapV3 is\n IPriceAdapter\n\n{\n \n\n\n\n\n struct PoolRoute {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n\n require( route_array.length ==1 || route_array.length ==2, \"invalid route length\" );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_adapters/PriceAdapterUniswapV4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/*\n\n see https://docs.uniswap.org/contracts/v4/deployments \n\n\n https://docs.uniswap.org/contracts/v4/guides/read-pool-state\n\n\n\n*/\n \n\n// Interfaces\nimport \"../interfaces/IPriceAdapter.sol\";\n\nimport {IStateView} from \"../interfaces/uniswapv4/IStateView.sol\";\n \nimport {FixedPointQ96} from \"../libraries/FixedPointQ96.sol\";\nimport {FullMath} from \"../libraries/uniswap/FullMath.sol\";\nimport {TickMath} from \"../libraries/uniswap/TickMath.sol\";\n\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\n\n\n\n\ncontract PriceAdapterUniswapV4 is\n IPriceAdapter\n\n{ \n\n \n\n using PoolIdLibrary for PoolKey;\n\n IPoolManager public immutable poolManager;\n\n\n using StateLibrary for IPoolManager;\n // address immutable POOL_MANAGER_V4; \n\n\n // 0x7ffe42c4a5deea5b0fec41c94c136cf115597227 on mainnet \n //address immutable UNISWAP_V4_STATE_VIEW; \n\n struct PoolRoute {\n PoolId pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n \n\n constructor(IPoolManager _poolManager) {\n poolManager = _poolManager;\n }\n\n\n\n\n \n mapping(bytes32 => bytes) public priceRoutes; \n \n \n\n\n /* Events */\n\n event RouteRegistered(bytes32 hash, bytes route);\n \n\n /* External Functions */\n \n \n function registerPriceRoute(\n bytes memory route\n ) external returns (bytes32 hash) {\n\n PoolRoute[] memory route_array = decodePoolRoutes( route );\n\n \t\t// hash the route with keccak256\n bytes32 poolRouteHash = keccak256(route);\n\n \t\t// store the route by its hash in the priceRoutes mapping\n priceRoutes[poolRouteHash] = route;\n\n emit RouteRegistered(poolRouteHash, route);\n\n return poolRouteHash;\n }\n\n \n\n\n\n function getPriceRatioQ96(\n bytes32 route\n ) external view returns ( uint256 priceRatioQ96 ) {\n\n // lookup the route from the mapping\n bytes memory routeData = priceRoutes[route];\n require(routeData.length > 0, \"Route not found\");\n\n // decode the route\n PoolRoute[] memory poolRoutes = decodePoolRoutes(routeData);\n\n // start with Q96 = 1.0 in Q96 format\n priceRatioQ96 = FixedPointQ96.Q96;\n\n // iterate through each pool and multiply prices\n for (uint256 i = 0; i < poolRoutes.length; i++) {\n uint256 poolPriceQ96 = getUniswapPriceRatioForPool(poolRoutes[i]);\n // multiply using Q96 arithmetic\n priceRatioQ96 = FixedPointQ96.multiplyFixedPoint96(priceRatioQ96, poolPriceQ96);\n }\n }\n\n\n\n // -------\n\n\n\n function encodePoolRoutes( PoolRoute[] memory routes ) public pure returns (bytes memory encoded) {\n\n encoded = abi.encode(routes);\n\n }\n\n\n // validate the route for length, other restrictions\n //must be length 1 or 2\n\n function decodePoolRoutes( bytes memory data ) public pure returns ( PoolRoute[] memory route_array ) {\n\n route_array = abi.decode(data, (PoolRoute[]));\n\n require(route_array.length == 1 || route_array.length == 2, \"Route must have 1 or 2 pools\");\n\n }\n\n\n\n\n // -------\n\n function getPoolState(PoolId poolId) internal view returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint24 protocolFee,\n uint24 lpFee\n ) {\n return poolManager.getSlot0(poolId);\n }\n\n\n\n\n\n function getUniswapPriceRatioForPool(\n PoolRoute memory _poolRoute\n ) internal view returns (uint256 priceRatioQ96) {\n\n // this is expanded by 2**96\n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRoute.pool,\n _poolRoute.twapInterval\n );\n\n // Convert sqrtPriceX96 to priceQ96\n // sqrtPriceX96^2 / 2^96 gives us the price in Q96 format\n priceRatioQ96 = getPriceQ96FromSqrtPriceX96(sqrtPriceX96);\n\n // If we need the inverse (token0 in terms of token1), invert\n bool invert = !_poolRoute.zeroForOne;\n if (invert) {\n // To invert a Q96 number: (Q96 * Q96) / value\n priceRatioQ96 = FullMath.mulDiv(FixedPointQ96.Q96, FixedPointQ96.Q96, priceRatioQ96);\n }\n }\n\n function getSqrtTwapX96(PoolId poolId, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n\n\n\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , ) = getPoolState(poolId);\n } else {\n\n revert(\"twap price not impl \");\n\n \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 getPriceQ96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceQ96)\n {\n // sqrtPriceX96^2 / 2^96 = priceQ96\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPointQ96.Q96);\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n}\n" + }, + "contracts/price_oracles/UniswapPricingHelper.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\n \n \n// Libraries \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 \n*/\n\ncontract UniswapPricingHelper\n{\n\n\n // use uniswap exp helper instead ? \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\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 /**\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). Taken directly from uniswap oracle lib \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/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/ReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n// Interfaces\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ReputationManager is IReputationManager, Initializable {\n using EnumerableSet for EnumerableSet.UintSet;\n\n bytes32 public constant CONTROLLER = keccak256(\"CONTROLLER\");\n\n ITellerV2 public tellerV2;\n mapping(address => EnumerableSet.UintSet) private _delinquencies;\n mapping(address => EnumerableSet.UintSet) private _defaults;\n mapping(address => EnumerableSet.UintSet) private _currentDelinquencies;\n mapping(address => EnumerableSet.UintSet) private _currentDefaults;\n\n event MarkAdded(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n event MarkRemoved(\n address indexed account,\n RepMark indexed repMark,\n uint256 bidId\n );\n\n /**\n * @notice Initializes the proxy.\n */\n function initialize(address _tellerV2) external initializer {\n tellerV2 = ITellerV2(_tellerV2);\n }\n\n function getDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _delinquencies[_account].values();\n }\n\n function getDefaultedLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _defaults[_account].values();\n }\n\n function getCurrentDelinquentLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDelinquencies[_account].values();\n }\n\n function getCurrentDefaultLoanIds(address _account)\n public\n override\n returns (uint256[] memory)\n {\n updateAccountReputation(_account);\n return _currentDefaults[_account].values();\n }\n\n function updateAccountReputation(address _account) public override {\n uint256[] memory activeBidIds = tellerV2.getBorrowerActiveLoanIds(\n _account\n );\n for (uint256 i; i < activeBidIds.length; i++) {\n _applyReputation(_account, activeBidIds[i]);\n }\n }\n\n function updateAccountReputation(address _account, uint256 _bidId)\n public\n override\n returns (RepMark)\n {\n return _applyReputation(_account, _bidId);\n }\n\n function _applyReputation(address _account, uint256 _bidId)\n internal\n returns (RepMark mark_)\n {\n mark_ = RepMark.Good;\n\n if (tellerV2.isLoanDefaulted(_bidId)) {\n mark_ = RepMark.Default;\n\n // Remove delinquent status\n _removeMark(_account, _bidId, RepMark.Delinquent);\n } else if (tellerV2.isPaymentLate(_bidId)) {\n mark_ = RepMark.Delinquent;\n }\n\n // Mark status if not \"Good\"\n if (mark_ != RepMark.Good) {\n _addMark(_account, _bidId, mark_);\n }\n }\n\n function _addMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _delinquencies[_account].add(_bidId);\n _currentDelinquencies[_account].add(_bidId);\n } else if (_mark == RepMark.Default) {\n _defaults[_account].add(_bidId);\n _currentDefaults[_account].add(_bidId);\n }\n\n emit MarkAdded(_account, _mark, _bidId);\n }\n\n function _removeMark(address _account, uint256 _bidId, RepMark _mark)\n internal\n {\n if (_mark == RepMark.Delinquent) {\n _currentDelinquencies[_account].remove(_bidId);\n } else if (_mark == RepMark.Default) {\n _currentDefaults[_account].remove(_bidId);\n }\n\n emit MarkRemoved(_account, _mark, _bidId);\n }\n}\n" + }, + "contracts/TellerV0Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n/*\n\n THIS IS ONLY USED FOR SUBGRAPH \n \n\n*/\n\ncontract TellerV0Storage {\n enum 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 */\n struct Payment {\n uint256 principal;\n uint256 interest;\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 */\n struct LoanDetails {\n ERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\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 */\n struct Bid0 {\n address borrower;\n address receiver;\n address _lender; // DEPRECATED\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\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 */\n struct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n }\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid0) public bids;\n}\n" + }, + "contracts/TellerV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"./ProtocolFee.sol\";\nimport \"./TellerV2Storage.sol\";\nimport \"./TellerV2Context.sol\";\nimport \"./pausing/HasProtocolPausingManager.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"; \nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\n\n// Interfaces\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"./interfaces/ITellerV2.sol\";\nimport { Collateral } from \"./interfaces/escrow/ICollateralEscrowV1.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"./interfaces/ILoanRepaymentCallbacks.sol\";\nimport \"./interfaces/ILoanRepaymentListener.sol\";\n\n// Libraries\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport {SafeERC20} from \"./openzeppelin/SafeERC20.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\nimport \"./libraries/ExcessivelySafeCall.sol\";\n\nimport { V2Calculations, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\n\n/* Errors */\n/**\n * @notice This error is reverted when the action isn't allowed\n * @param bidId The id of the bid.\n * @param action The action string (i.e: 'repayLoan', 'cancelBid', 'etc)\n * @param message The message string to return to the user explaining why the tx was reverted\n */\nerror ActionNotAllowed(uint256 bidId, string action, string message);\n\n/**\n * @notice This error is reverted when repayment amount is less than the required minimum\n * @param bidId The id of the bid the borrower is attempting to repay.\n * @param payment The payment made by the borrower\n * @param minimumOwed The minimum owed value\n */\nerror PaymentNotMinimum(uint256 bidId, uint256 payment, uint256 minimumOwed);\n\ncontract TellerV2 is\n ITellerV2,\n ILoanRepaymentCallbacks,\n OwnableUpgradeable,\n ProtocolFee,\n HasProtocolPausingManager,\n TellerV2Storage,\n TellerV2Context\n{\n using Address for address;\n using SafeERC20 for IERC20;\n using NumbersLib for uint256;\n using EnumerableSet for EnumerableSet.AddressSet;\n using EnumerableSet for EnumerableSet.UintSet;\n\n //the first 20 bytes of keccak256(\"lender manager\")\n address constant USING_LENDER_MANAGER =\n 0x84D409EeD89F6558fE3646397146232665788bF8;\n\n /** Events */\n\n /**\n * @notice This event is emitted when a new bid is submitted.\n * @param bidId The id of the bid submitted.\n * @param borrower The address of the bid borrower.\n * @param metadataURI URI for additional bid information as part of loan bid.\n */\n event SubmittedBid(\n uint256 indexed bidId,\n address indexed borrower,\n address receiver,\n bytes32 indexed metadataURI\n );\n\n /**\n * @notice This event is emitted when a bid has been accepted by a lender.\n * @param bidId The id of the bid accepted.\n * @param lender The address of the accepted bid lender.\n */\n event AcceptedBid(uint256 indexed bidId, address indexed lender);\n\n /**\n * @notice This event is emitted when a previously submitted bid has been cancelled.\n * @param bidId The id of the cancelled bid.\n */\n event CancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when market owner has cancelled a pending bid in their market.\n * @param bidId The id of the bid funded.\n *\n * Note: The `CancelledBid` event will also be emitted.\n */\n event MarketOwnerCancelledBid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a payment is made towards an active loan.\n * @param bidId The id of the bid/loan to which the payment was made.\n */\n event LoanRepayment(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanRepaid(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been closed by a lender to claim collateral.\n * @param bidId The id of the bid accepted.\n */\n event LoanClosed(uint256 indexed bidId);\n\n /**\n * @notice This event is emitted when a loan has been fully repaid.\n * @param bidId The id of the bid/loan which was repaid.\n */\n event LoanLiquidated(uint256 indexed bidId, address indexed liquidator);\n\n /**\n * @notice This event is emitted when a fee has been paid related to a bid.\n * @param bidId The id of the bid.\n * @param feeType The name of the fee being paid.\n * @param amount The amount of the fee being paid.\n */\n event FeePaid(\n uint256 indexed bidId,\n string indexed feeType,\n uint256 indexed amount\n );\n\n /** Modifiers */\n\n /**\n * @notice This modifier is used to check if the state of a bid is pending, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier pendingBid(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.PENDING) {\n revert ActionNotAllowed(_bidId, _action, \"Bid not pending\");\n }\n\n _;\n }\n\n /**\n * @notice This modifier is used to check if the state of a loan has been accepted, before running an action.\n * @param _bidId The id of the bid to check the state for.\n * @param _action The desired action to run on the bid.\n */\n modifier acceptedLoan(uint256 _bidId, string memory _action) {\n if (bids[_bidId].state != BidState.ACCEPTED) {\n revert ActionNotAllowed(_bidId, _action, \"Loan not accepted\");\n }\n\n _;\n }\n\n\n /** Constant Variables **/\n\n uint8 public constant CURRENT_CODE_VERSION = 10;\n\n uint32 public constant LIQUIDATION_DELAY = 86400; //ONE DAY IN SECONDS\n\n /** Constructor **/\n\n constructor(address trustedForwarder) TellerV2Context(trustedForwarder) {}\n\n /** External Functions **/\n\n /**\n * @notice Initializes the proxy.\n * @param _protocolFee The fee collected by the protocol for loan processing.\n * @param _marketRegistry The address of the market registry contract for the protocol.\n * @param _reputationManager The address of the reputation manager contract.\n * @param _lenderCommitmentForwarder The address of the lender commitment forwarder contract.\n * @param _collateralManager The address of the collateral manager contracts.\n * @param _lenderManager The address of the lender manager contract for loans on the protocol.\n * @param _protocolPausingManager The address of the pausing manager contract for the protocol.\n */\n function initialize(\n uint16 _protocolFee,\n address _marketRegistry,\n address _reputationManager,\n address _lenderCommitmentForwarder,\n address _collateralManager,\n address _lenderManager,\n address _escrowVault,\n address _protocolPausingManager\n ) external initializer {\n __ProtocolFee_init(_protocolFee);\n\n //__Pausable_init();\n\n require(\n _lenderCommitmentForwarder.isContract(),\n \"LCF_ic\"\n );\n lenderCommitmentForwarder = _lenderCommitmentForwarder;\n\n require(\n _marketRegistry.isContract(),\n \"MR_ic\"\n );\n marketRegistry = IMarketRegistry(_marketRegistry);\n\n require(\n _reputationManager.isContract(),\n \"RM_ic\"\n );\n reputationManager = IReputationManager(_reputationManager);\n\n require(\n _collateralManager.isContract(),\n \"CM_ic\"\n );\n collateralManager = ICollateralManager(_collateralManager);\n\n \n \n require(\n _lenderManager.isContract(),\n \"LM_ic\"\n );\n lenderManager = ILenderManager(_lenderManager);\n\n\n \n\n require(_escrowVault.isContract(), \"EV_ic\");\n escrowVault = IEscrowVault(_escrowVault);\n\n\n\n\n _setProtocolPausingManager(_protocolPausingManager);\n }\n\n \n \n \n \n /**\n * @notice Function for a borrower to create a bid for a loan without 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 */\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n }\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 ) public override whenProtocolNotPaused returns (uint256 bidId_) {\n bidId_ = _submitBid(\n _lendingToken,\n _marketplaceId,\n _principal,\n _duration,\n _APR,\n _metadataURI,\n _receiver\n );\n\n bool validation = collateralManager.commitCollateral(\n bidId_,\n _collateralInfo\n );\n\n require(\n validation == true,\n \"C bal NV\"\n );\n }\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 ) internal virtual returns (uint256 bidId_) {\n address sender = _msgSenderForMarket(_marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedBorrower(\n _marketplaceId,\n sender\n );\n\n require(isVerified, \"Borrower NV\");\n\n require(\n marketRegistry.isMarketOpen(_marketplaceId),\n \"Mkt C\"\n );\n\n // Set response bid ID.\n bidId_ = bidId;\n\n // Create and store our bid into the mapping\n Bid storage bid = bids[bidId];\n bid.borrower = sender;\n bid.receiver = _receiver != address(0) ? _receiver : bid.borrower;\n bid.marketplaceId = _marketplaceId;\n bid.loanDetails.lendingToken = IERC20(_lendingToken);\n bid.loanDetails.principal = _principal;\n bid.loanDetails.loanDuration = _duration;\n bid.loanDetails.timestamp = uint32(block.timestamp);\n\n // Set payment cycle type based on market setting (custom or monthly)\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\n .getPaymentCycle(_marketplaceId);\n\n bid.terms.APR = _APR;\n\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\n _marketplaceId\n );\n\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\n _marketplaceId\n );\n\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\n\n bid.terms.paymentCycleAmount = V2Calculations\n .calculatePaymentCycleAmount(\n bid.paymentType,\n bidPaymentCycleType[bidId],\n _principal,\n _duration,\n bid.terms.paymentCycle,\n _APR\n );\n\n uris[bidId] = _metadataURI;\n bid.state = BidState.PENDING;\n\n emit SubmittedBid(\n bidId,\n bid.borrower,\n bid.receiver,\n keccak256(abi.encodePacked(_metadataURI))\n );\n\n // Store bid inside borrower bids mapping\n borrowerBids[bid.borrower].push(bidId);\n\n // Increment bid id counter\n bidId++;\n }\n\n /**\n * @notice Function for a borrower to cancel their pending bid.\n * @param _bidId The id of the bid to cancel.\n */\n function cancelBid(uint256 _bidId) external {\n if (\n _msgSenderForMarket(bids[_bidId].marketplaceId) !=\n bids[_bidId].borrower\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"CB\",\n message: \"Not bid owner\" //this is a TON of storage space\n });\n }\n _cancelBid(_bidId);\n }\n\n /**\n * @notice Function for a market owner to cancel a bid in the market.\n * @param _bidId The id of the bid to cancel.\n */\n function marketOwnerCancelBid(uint256 _bidId) external {\n if (\n _msgSender() !=\n marketRegistry.getMarketOwner(bids[_bidId].marketplaceId)\n ) {\n revert ActionNotAllowed({\n bidId: _bidId,\n action: \"MOCB\",\n message: \"Not market owner\" //this is a TON of storage space \n });\n }\n _cancelBid(_bidId);\n emit MarketOwnerCancelledBid(_bidId);\n }\n\n /**\n * @notice Function for users to cancel a bid.\n * @param _bidId The id of the bid to be cancelled.\n */\n function _cancelBid(uint256 _bidId)\n internal\n virtual\n pendingBid(_bidId, \"cb\")\n {\n // Set the bid state to CANCELLED\n bids[_bidId].state = BidState.CANCELLED;\n\n // Emit CancelledBid event\n emit CancelledBid(_bidId);\n }\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 override\n pendingBid(_bidId, \"lab\")\n whenProtocolNotPaused\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n )\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n (bool isVerified, ) = marketRegistry.isVerifiedLender(\n bid.marketplaceId,\n sender\n );\n require(isVerified, \"NV\");\n\n require(\n !marketRegistry.isMarketClosed(bid.marketplaceId),\n \"Market is closed\"\n );\n\n require(!isLoanExpired(_bidId), \"BE\");\n\n // Set timestamp\n bid.loanDetails.acceptedTimestamp = uint32(block.timestamp);\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n\n // Mark borrower's request as accepted\n bid.state = BidState.ACCEPTED;\n\n // Declare the bid acceptor as the lender of the bid\n bid.lender = sender;\n\n // Tell the collateral manager to deploy the escrow and pull funds from the borrower if applicable\n collateralManager.deployAndDeposit(_bidId);\n\n // Transfer funds to borrower from the lender\n amountToProtocol = bid.loanDetails.principal.percent(protocolFee());\n amountToMarketplace = bid.loanDetails.principal.percent(\n marketRegistry.getMarketplaceFee(bid.marketplaceId)\n );\n amountToBorrower =\n bid.loanDetails.principal -\n amountToProtocol -\n amountToMarketplace;\n\n //transfer fee to protocol\n if (amountToProtocol > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n _getProtocolFeeRecipient(),\n amountToProtocol\n );\n }\n\n //transfer fee to marketplace\n if (amountToMarketplace > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n marketRegistry.getMarketFeeRecipient(bid.marketplaceId),\n amountToMarketplace\n );\n }\n\n//local stack scope\n{\n uint256 balanceBefore = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n ); \n\n //transfer funds to borrower\n if (amountToBorrower > 0) {\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n bid.receiver,\n amountToBorrower\n );\n }\n\n uint256 balanceAfter = bid.loanDetails.lendingToken.balanceOf(\n address(bid.receiver)\n );\n\n //used to revert for fee-on-transfer tokens as principal \n uint256 paymentAmountReceived = balanceAfter - balanceBefore;\n require(amountToBorrower == paymentAmountReceived, \"UT\"); \n}\n\n\n // Record volume filled by lenders\n lenderVolumeFilled[address(bid.loanDetails.lendingToken)][sender] += bid\n .loanDetails\n .principal;\n totalVolumeFilled[address(bid.loanDetails.lendingToken)] += bid\n .loanDetails\n .principal;\n\n // Add borrower's active bid\n _borrowerBidsActive[bid.borrower].add(_bidId);\n\n // Emit AcceptedBid\n emit AcceptedBid(_bidId, sender);\n\n emit FeePaid(_bidId, \"protocol\", amountToProtocol);\n emit FeePaid(_bidId, \"marketplace\", amountToMarketplace);\n }\n\n function claimLoanNFT(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"cln\")\n whenProtocolNotPaused\n {\n // Retrieve bid\n Bid storage bid = bids[_bidId];\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == bid.lender, \"NV Lender\");\n\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\n bid.lender = address(USING_LENDER_MANAGER);\n\n // mint an NFT with the lender manager\n lenderManager.registerLoan(_bidId, sender);\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: duePrincipal, interest: interest }),\n owedPrincipal + interest,\n true\n );\n }\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, true);\n }\n\n // function that the borrower (ideally) sends to repay the loan\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)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, true);\n }\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 repayLoanFullWithoutCollateralWithdraw(uint256 _bidId)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanFull(_bidId, false);\n }\n\n function repayLoanWithoutCollateralWithdraw(uint256 _bidId, uint256 _amount)\n external\n acceptedLoan(_bidId, \"rl\")\n {\n _repayLoanAtleastMinimum(_bidId, _amount, false);\n }\n\n function _repayLoanFull(uint256 _bidId, bool withdrawCollateral) internal {\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n function _repayLoanAtleastMinimum(\n uint256 _bidId,\n uint256 _amount,\n bool withdrawCollateral\n ) internal {\n (\n uint256 owedPrincipal,\n uint256 duePrincipal,\n uint256 interest\n ) = V2Calculations.calculateAmountOwed(\n bids[_bidId],\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n uint256 minimumOwed = duePrincipal + interest;\n\n // If amount is less than minimumOwed, we revert\n if (_amount < minimumOwed) {\n revert PaymentNotMinimum(_bidId, _amount, minimumOwed);\n }\n\n _repayLoan(\n _bidId,\n Payment({ principal: _amount - interest, interest: interest }),\n owedPrincipal + interest,\n withdrawCollateral\n );\n }\n\n \n\n\n function lenderCloseLoan(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"lcc\")\n {\n Bid storage bid = bids[_bidId];\n address _collateralRecipient = getLoanLender(_bidId);\n\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n /**\n * @notice Function for lender to claim collateral for a defaulted loan. The only purpose of a CLOSED loan is to make collateral claimable by lender.\n * @param _bidId The id of the loan to set to CLOSED status.\n */\n function lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) external whenProtocolNotPaused whenLiquidationsNotPaused {\n _lenderCloseLoanWithRecipient(_bidId, _collateralRecipient);\n }\n\n function _lenderCloseLoanWithRecipient(\n uint256 _bidId,\n address _collateralRecipient\n ) internal acceptedLoan(_bidId, \"lcc\") {\n require(isLoanDefaulted(_bidId), \"ND\");\n\n Bid storage bid = bids[_bidId];\n bid.state = BidState.CLOSED;\n\n address sender = _msgSenderForMarket(bid.marketplaceId);\n require(sender == getLoanLender(_bidId), \"NLL\");\n\n \n collateralManager.lenderClaimCollateralWithRecipient(_bidId, _collateralRecipient);\n\n emit LoanClosed(_bidId);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function liquidateLoanFull(uint256 _bidId)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n Bid storage bid = bids[_bidId];\n\n // If loan is backed by collateral, withdraw and send to the liquidator\n address recipient = _msgSenderForMarket(bid.marketplaceId);\n\n _liquidateLoanFull(_bidId, recipient);\n }\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external whenProtocolNotPaused whenLiquidationsNotPaused\n acceptedLoan(_bidId, \"ll\")\n {\n _liquidateLoanFull(_bidId, _recipient);\n }\n\n /**\n * @notice Function for users to liquidate a defaulted loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function _liquidateLoanFull(uint256 _bidId, address _recipient)\n internal\n acceptedLoan(_bidId, \"ll\")\n {\n require(isLoanLiquidateable(_bidId), \"NL\");\n\n Bid storage bid = bids[_bidId];\n\n // change state here to prevent re-entrancy\n bid.state = BidState.LIQUIDATED;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n block.timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n //this sets the state to 'repaid'\n _repayLoan(\n _bidId,\n Payment({ principal: owedPrincipal, interest: interest }),\n owedPrincipal + interest,\n false\n );\n\n collateralManager.liquidateCollateral(_bidId, _recipient);\n\n address liquidator = _msgSenderForMarket(bid.marketplaceId);\n\n emit LoanLiquidated(_bidId, liquidator);\n }\n\n /**\n * @notice Internal function to make a loan payment.\n * @dev Updates the bid's `status` to `PAID` only if it is not already marked as `LIQUIDATED`\n * @param _bidId The id of the loan to make the payment towards.\n * @param _payment The Payment struct with payments amounts towards principal and interest respectively.\n * @param _owedAmount The total amount owed on the loan.\n */\n function _repayLoan(\n uint256 _bidId,\n Payment memory _payment,\n uint256 _owedAmount,\n bool _shouldWithdrawCollateral\n ) internal virtual {\n Bid storage bid = bids[_bidId];\n uint256 paymentAmount = _payment.principal + _payment.interest;\n\n RepMark mark = reputationManager.updateAccountReputation(\n bid.borrower,\n _bidId\n );\n\n // Check if we are sending a payment or amount remaining\n if (paymentAmount >= _owedAmount) {\n paymentAmount = _owedAmount;\n\n if (bid.state != BidState.LIQUIDATED) {\n bid.state = BidState.PAID;\n }\n\n // Remove borrower's active bid\n _borrowerBidsActive[bid.borrower].remove(_bidId);\n\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\n if (_shouldWithdrawCollateral) { \n \n // _getCollateralManagerForBid(_bidId).withdraw(_bidId);\n collateralManager.withdraw(_bidId);\n }\n\n emit LoanRepaid(_bidId);\n } else {\n emit LoanRepayment(_bidId);\n }\n\n \n\n // update our mappings\n bid.loanDetails.totalRepaid.principal += _payment.principal;\n bid.loanDetails.totalRepaid.interest += _payment.interest;\n bid.loanDetails.lastRepaidTimestamp = uint32(block.timestamp);\n \n //perform this after state change to mitigate re-entrancy\n _sendOrEscrowFunds(_bidId, _payment); //send or escrow the funds\n\n // If the loan is paid in full and has a mark, we should update the current reputation\n if (mark != RepMark.Good) {\n reputationManager.updateAccountReputation(bid.borrower, _bidId);\n }\n }\n\n\n /*\n If for some reason the lender cannot receive funds, should put those funds into the escrow \n so the loan can always be repaid and the borrower can get collateral out \n \n\n */\n function _sendOrEscrowFunds(uint256 _bidId, Payment memory _payment)\n internal virtual \n {\n Bid storage bid = bids[_bidId];\n address lender = getLoanLender(_bidId);\n\n uint256 _paymentAmount = _payment.principal + _payment.interest;\n\n //USER STORY: Should function properly with USDT and USDC and WETH for sure \n\n //USER STORY : if the lender cannot receive funds for some reason (denylisted) \n //then we will try to send the funds to the EscrowContract bc we want the borrower to be able to get back their collateral ! \n // i.e. lender not being able to recieve funds should STILL allow repayment to succeed ! \n\n \n bool transferSuccess = safeTransferFromERC20Custom( \n address(bid.loanDetails.lendingToken),\n _msgSenderForMarket(bid.marketplaceId) , //from\n lender, //to\n _paymentAmount // amount \n );\n \n if (!transferSuccess) { \n //could not send funds due to an issue with lender (denylisted?) so we are going to try and send the funds to the\n // escrow wallet FOR the lender to be able to retrieve at a later time when they are no longer denylisted by the token \n \n address sender = _msgSenderForMarket(bid.marketplaceId);\n\n // fee on transfer tokens are not supported in the lenderAcceptBid step\n\n //if unable, pay to escrow\n bid.loanDetails.lendingToken.safeTransferFrom(\n sender,\n address(this),\n _paymentAmount\n ); \n\n bid.loanDetails.lendingToken.forceApprove(\n address(escrowVault),\n _paymentAmount\n );\n\n IEscrowVault(escrowVault).deposit(\n lender,\n address(bid.loanDetails.lendingToken),\n _paymentAmount\n );\n\n\n }\n\n address loanRepaymentListener = repaymentListenerForBid[_bidId];\n\n if (loanRepaymentListener != address(0)) {\n \n \n \n\n //make sure the external call will not fail due to out-of-gas\n require(gasleft() >= 80000, \"NR gas\"); //fixes the 63/64 remaining issue\n\n bool repayCallbackSucccess = safeRepayLoanCallback(\n loanRepaymentListener,\n _bidId,\n _msgSenderForMarket(bid.marketplaceId),\n _payment.principal,\n _payment.interest\n ); \n\n\n }\n }\n\n\n function safeRepayLoanCallback(\n address _loanRepaymentListener,\n uint256 _bidId,\n address _sender,\n uint256 _principal,\n uint256 _interest\n ) internal virtual returns (bool) {\n\n //The EVM will only forward 63/64 of the remaining gas to the external call to _loanRepaymentListener.\n\n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_loanRepaymentListener),\n 80000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n ILoanRepaymentListener\n .repayLoanCallback\n .selector,\n _bidId,\n _sender,\n _principal,\n _interest \n ) \n );\n\n\n return callSuccess ;\n }\n\n /*\n A try/catch pattern for safeTransferERC20 that helps support standard ERC20 tokens and non-standard ones like USDT \n\n @notice If the token address is an EOA, callSuccess will always be true so token address should always be a contract. \n */\n function safeTransferFromERC20Custom(\n\n address _token,\n address _from,\n address _to,\n uint256 _amount \n\n ) internal virtual returns (bool success) {\n\n //https://github.com/nomad-xyz/ExcessivelySafeCall\n //this works similarly to a try catch -- an inner revert doesnt revert us but will make callSuccess be false. \n ( bool callSuccess, bytes memory callReturnData ) = ExcessivelySafeCall.excessivelySafeCall(\n address(_token),\n 100000, //max gas \n 0, //value (eth) to send in call\n 1000, //max return data size \n abi.encodeWithSelector(\n IERC20\n .transferFrom\n .selector,\n _from,\n _to,\n _amount\n ) \n );\n \n\n //If the token returns data, make sure it returns true. This helps us with USDT which may revert but never returns a bool.\n bool dataIsSuccess = true;\n if (callReturnData.length >= 32) {\n assembly {\n // Load the first 32 bytes of the return data (assuming it's a bool)\n let result := mload(add(callReturnData, 0x20))\n // Check if the result equals `true` (1)\n dataIsSuccess := eq(result, 1)\n }\n }\n\n // ensures that both callSuccess (the low-level call didn't fail) and dataIsSuccess (the function returned true if it returned something).\n return callSuccess && dataIsSuccess; \n\n\n }\n\n\n /**\n * @notice Calculates the total amount owed for a loan bid at a specific timestamp.\n * @param _bidId The id of the loan bid to calculate the owed amount for.\n * @param _timestamp The timestamp at which to calculate the loan owed amount at.\n */\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory owed)\n {\n Bid storage bid = bids[_bidId];\n if (\n bid.state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return owed;\n\n (uint256 owedPrincipal, , uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n\n owed.principal = owedPrincipal;\n owed.interest = interest;\n }\n\n /**\n * @notice Calculates the minimum payment amount due for a loan at a specific timestamp.\n * @param _bidId The id of the loan bid to get the payment amount for.\n * @param _timestamp The timestamp at which to get the due payment at.\n */\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n public\n view\n returns (Payment memory due)\n {\n Bid storage bid = bids[_bidId];\n if (\n bids[_bidId].state != BidState.ACCEPTED ||\n bid.loanDetails.acceptedTimestamp >= _timestamp\n ) return due;\n\n (, uint256 duePrincipal, uint256 interest) = V2Calculations\n .calculateAmountOwed(\n bid,\n _timestamp,\n _getBidPaymentCycleType(_bidId),\n _getBidPaymentCycleDuration(_bidId)\n );\n due.principal = duePrincipal;\n due.interest = interest;\n }\n\n /**\n * @notice Returns the next due date for a loan payment.\n * @param _bidId The id of the loan bid.\n */\n function calculateNextDueDate(uint256 _bidId)\n public\n view\n returns (uint32 dueDate_)\n {\n Bid storage bid = bids[_bidId];\n if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\n\n return\n V2Calculations.calculateNextDueDate(\n bid.loanDetails.acceptedTimestamp,\n bid.terms.paymentCycle,\n bid.loanDetails.loanDuration,\n lastRepaidTimestamp(_bidId),\n bidPaymentCycleType[_bidId]\n );\n }\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) public view override returns (bool) {\n if (bids[_bidId].state != BidState.ACCEPTED) return false;\n return uint32(block.timestamp) > calculateNextDueDate(_bidId);\n }\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 * @return bool True if the loan is defaulted.\n */\n function isLoanDefaulted(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, 0);\n }\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 * @return bool True if the loan is liquidateable.\n */\n function isLoanLiquidateable(uint256 _bidId)\n public\n view\n override\n returns (bool)\n {\n return _isLoanDefaulted(_bidId, LIQUIDATION_DELAY);\n }\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 * @param _additionalDelay Amount of additional seconds after a loan defaulted to allow a liquidation.\n * @return bool True if the loan is liquidateable.\n */\n function _isLoanDefaulted(uint256 _bidId, uint32 _additionalDelay)\n internal\n view\n returns (bool)\n {\n Bid storage bid = bids[_bidId];\n\n // Make sure loan cannot be liquidated if it is not active\n if (bid.state != BidState.ACCEPTED) return false;\n\n uint32 defaultDuration = bidDefaultDuration[_bidId];\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return\n uint32(block.timestamp) >\n dueDate + defaultDuration + _additionalDelay;\n }\n\n function getEscrowVault() external view returns(address){\n return address(escrowVault);\n }\n\n function getBidState(uint256 _bidId)\n external\n view\n override\n returns (BidState)\n {\n return bids[_bidId].state;\n }\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n override\n returns (uint256[] memory)\n {\n return _borrowerBidsActive[_borrower].values();\n }\n\n function getBorrowerLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory)\n {\n return borrowerBids[_borrower];\n }\n\n /**\n * @notice Checks to see if a pending loan has expired so it is no longer able to be accepted.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanExpired(uint256 _bidId) public view returns (bool) {\n Bid storage bid = bids[_bidId];\n\n if (bid.state != BidState.PENDING) return false;\n if (bidExpirationTime[_bidId] == 0) return false;\n\n return (uint32(block.timestamp) >\n bid.loanDetails.timestamp + bidExpirationTime[_bidId]);\n }\n\n /**\n * @notice Returns the last repaid timestamp for a loan.\n * @param _bidId The id of the loan bid to get the timestamp for.\n */\n function lastRepaidTimestamp(uint256 _bidId) public view returns (uint32) {\n return V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n }\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 public\n view\n returns (address borrower_)\n {\n borrower_ = bids[_bidId].borrower;\n }\n\n /**\n * @notice Returns the lender address for a given bid. If the stored lender address is the `LenderManager` NFT address, return the `ownerOf` for the bid ID.\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 public\n view\n returns (address lender_)\n {\n lender_ = bids[_bidId].lender;\n\n if (lender_ == address(USING_LENDER_MANAGER)) {\n return lenderManager.ownerOf(_bidId);\n }\n\n //this is left in for backwards compatibility only\n if (lender_ == address(lenderManager)) {\n return lenderManager.ownerOf(_bidId);\n }\n }\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_)\n {\n token_ = address(bids[_bidId].loanDetails.lendingToken);\n }\n\n function getLoanMarketId(uint256 _bidId)\n external\n view\n returns (uint256 _marketId)\n {\n _marketId = bids[_bidId].marketplaceId;\n }\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 Bid storage bid = bids[_bidId];\n\n borrower = bid.borrower;\n lender = getLoanLender(_bidId);\n marketId = bid.marketplaceId;\n principalTokenAddress = address(bid.loanDetails.lendingToken);\n principalAmount = bid.loanDetails.principal;\n acceptedTimestamp = bid.loanDetails.acceptedTimestamp;\n lastRepaidTimestamp = V2Calculations.lastRepaidTimestamp(bids[_bidId]);\n bidState = bid.state;\n }\n\n // Additions for lender groups\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n public\n view\n returns (uint256)\n {\n Bid storage bid = bids[_bidId];\n\n uint32 defaultDuration = _getBidDefaultDuration(_bidId);\n\n uint32 dueDate = calculateNextDueDate(_bidId);\n\n return dueDate + defaultDuration;\n }\n \n function setRepaymentListenerForBid(uint256 _bidId, address _listener) external {\n uint256 codeSize;\n assembly {\n codeSize := extcodesize(_listener) \n }\n require(codeSize > 0, \"Not a contract\");\n address sender = _msgSenderForMarket(bids[_bidId].marketplaceId);\n\n require(\n sender == getLoanLender(_bidId),\n \"Not lender\"\n );\n\n repaymentListenerForBid[_bidId] = _listener;\n }\n\n\n\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address)\n {\n return repaymentListenerForBid[_bidId];\n }\n\n // ----------\n\n function _getBidPaymentCycleType(uint256 _bidId)\n internal\n view\n returns (PaymentCycleType)\n {\n \n\n return bidPaymentCycleType[_bidId];\n }\n\n function _getBidPaymentCycleDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n Bid storage bid = bids[_bidId];\n\n return bid.terms.paymentCycle;\n }\n\n function _getBidDefaultDuration(uint256 _bidId)\n internal\n view\n returns (uint32)\n {\n \n\n return bidDefaultDuration[_bidId];\n }\n\n\n\n function _getProtocolFeeRecipient()\n internal view\n returns (address) {\n\n if (protocolFeeRecipient == address(0x0)){\n return owner();\n }else {\n return protocolFeeRecipient; \n }\n\n }\n\n function getProtocolFeeRecipient()\n external view\n returns (address) {\n\n return _getProtocolFeeRecipient();\n\n }\n\n function setProtocolFeeRecipient(address _recipient)\n external onlyOwner\n {\n\n protocolFeeRecipient = _recipient;\n\n }\n\n // -----\n\n /** OpenZeppelin Override Functions **/\n\n function _msgSender()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (address sender)\n {\n sender = ERC2771ContextUpgradeable._msgSender();\n }\n\n function _msgData()\n internal\n view\n virtual\n override(ERC2771ContextUpgradeable, ContextUpgradeable)\n returns (bytes calldata)\n {\n return ERC2771ContextUpgradeable._msgData();\n }\n}\n" + }, + "contracts/TellerV2Autopay.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\nimport \"./interfaces/ITellerV2Autopay.sol\";\n\nimport \"./libraries/NumbersLib.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { Payment } from \"./TellerV2Storage.sol\";\n\n/**\n * @dev Helper contract to autopay loans\n */\ncontract TellerV2Autopay is OwnableUpgradeable, ITellerV2Autopay {\n using SafeERC20 for ERC20;\n using NumbersLib for uint256;\n\n ITellerV2 public immutable tellerV2;\n\n //bidId => enabled\n mapping(uint256 => bool) public loanAutoPayEnabled;\n\n // Autopay fee set for automatic loan payments\n uint16 private _autopayFee;\n\n /**\n * @notice This event is emitted when a loan is autopaid.\n * @param bidId The id of the bid/loan which was repaid.\n * @param msgsender The account that called the method\n */\n event AutoPaidLoanMinimum(uint256 indexed bidId, address indexed msgsender);\n\n /**\n * @notice This event is emitted when loan autopayments are enabled or disabled.\n * @param bidId The id of the bid/loan.\n * @param enabled Whether the autopayments are enabled or disabled\n */\n event AutoPayEnabled(uint256 indexed bidId, bool enabled);\n\n /**\n * @notice This event is emitted when the autopay fee has been updated.\n * @param newFee The new autopay fee set.\n * @param oldFee The previously set autopay fee.\n */\n event AutopayFeeSet(uint16 newFee, uint16 oldFee);\n\n constructor(address _protocolAddress) {\n tellerV2 = ITellerV2(_protocolAddress);\n }\n\n /**\n * @notice Initialized the proxy.\n * @param _fee The fee collected for automatic payment processing.\n * @param _owner The address of the ownership to be transferred to.\n */\n function initialize(uint16 _fee, address _owner) external initializer {\n _transferOwnership(_owner);\n _setAutopayFee(_fee);\n }\n\n /**\n * @notice Let the owner of the contract set a new autopay fee.\n * @param _newFee The new autopay fee to set.\n */\n function setAutopayFee(uint16 _newFee) public virtual onlyOwner {\n _setAutopayFee(_newFee);\n }\n\n function _setAutopayFee(uint16 _newFee) internal {\n // Skip if the fee is the same\n if (_newFee == _autopayFee) return;\n uint16 oldFee = _autopayFee;\n _autopayFee = _newFee;\n emit AutopayFeeSet(_newFee, oldFee);\n }\n\n /**\n * @notice Returns the current autopay fee.\n */\n function getAutopayFee() public view virtual returns (uint16) {\n return _autopayFee;\n }\n\n /**\n * @notice Function for a borrower to enable or disable autopayments\n * @param _bidId The id of the bid to cancel.\n * @param _autoPayEnabled boolean for allowing autopay on a loan\n */\n function setAutoPayEnabled(uint256 _bidId, bool _autoPayEnabled) external {\n require(\n _msgSender() == tellerV2.getLoanBorrower(_bidId),\n \"Only the borrower can set autopay\"\n );\n\n loanAutoPayEnabled[_bidId] = _autoPayEnabled;\n\n emit AutoPayEnabled(_bidId, _autoPayEnabled);\n }\n\n /**\n * @notice Function for a minimum autopayment to be performed on a loan\n * @param _bidId The id of the bid to repay.\n */\n function autoPayLoanMinimum(uint256 _bidId) external {\n require(\n loanAutoPayEnabled[_bidId],\n \"Autopay is not enabled for that loan\"\n );\n\n address lendingToken = ITellerV2(tellerV2).getLoanLendingToken(_bidId);\n address borrower = ITellerV2(tellerV2).getLoanBorrower(_bidId);\n\n uint256 amountToRepayMinimum = getEstimatedMinimumPayment(\n _bidId,\n block.timestamp\n );\n uint256 autopayFeeAmount = amountToRepayMinimum.percent(\n getAutopayFee()\n );\n\n // Pull lendingToken in from the borrower to this smart contract\n ERC20(lendingToken).safeTransferFrom(\n borrower,\n address(this),\n amountToRepayMinimum + autopayFeeAmount\n );\n\n // Transfer fee to msg sender\n ERC20(lendingToken).safeTransfer(_msgSender(), autopayFeeAmount);\n\n // Approve the lendingToken to tellerV2\n ERC20(lendingToken).approve(address(tellerV2), amountToRepayMinimum);\n\n // Use that lendingToken to repay the loan\n tellerV2.repayLoan(_bidId, amountToRepayMinimum);\n\n emit AutoPaidLoanMinimum(_bidId, msg.sender);\n }\n\n function getEstimatedMinimumPayment(uint256 _bidId, uint256 _timestamp)\n public\n virtual\n returns (uint256 _amount)\n {\n Payment memory estimatedPayment = tellerV2.calculateAmountDue(\n _bidId,\n _timestamp\n );\n\n _amount = estimatedPayment.principal + estimatedPayment.interest;\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/type-imports.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/token/ERC20/presets/ERC20PresetMinterPauser.sol\";\n\nimport \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\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" + }, + "contracts/uniswap/v3-periphery/contracts/lens/Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\npragma abicoder v2;\n \n// ----\n\nimport {IUniswapV3Factory} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\nimport {IUniswapV3Pool} from '../../../../libraries/uniswap/core/interfaces/IUniswapV3Pool.sol';\nimport {SwapMath} from '../../../../libraries/uniswap/SwapMath.sol';\nimport {FullMath} from '../../../../libraries/uniswap/FullMath.sol';\nimport {TickMath} from '../../../../libraries/uniswap/TickMath.sol';\n\nimport '../../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\nimport '../../../../libraries/uniswap/core/libraries/SafeCast.sol';\nimport '../../../../libraries/uniswap/periphery/libraries/Path.sol';\n\nimport {SqrtPriceMath} from '../../../../libraries/uniswap/SqrtPriceMath.sol';\nimport {LiquidityMath} from '../../../../libraries/uniswap/LiquidityMath.sol';\nimport {PoolTickBitmap} from '../../../../libraries/uniswap/PoolTickBitmap.sol';\nimport {IQuoter} from '../../../../libraries/uniswap/periphery/interfaces/IQuoter.sol';\n\nimport {PoolAddress} from '../../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport {QuoterMath} from '../../../../libraries/uniswap/QuoterMath.sol';\n\n// ---\n\n\n\ncontract Quoter is IQuoter {\n using QuoterMath for *;\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Path for bytes;\n\n // The v3 factory address\n address public immutable factory;\n\n constructor(address _factory) {\n factory = _factory;\n }\n\n function getPool(address tokenA, address tokenB, uint24 fee) private view returns (address pool) {\n // pool = PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n\n pool = IUniswapV3Factory( factory )\n .getPool( tokenA, tokenB, fee );\n\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingleWithPool(QuoteExactInputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n // we need to pack a few variables to get under the stack limit\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96,\n exactInput: false\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, params.amountIn.toInt256(), quoteParams);\n\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInputSingle(QuoteExactInputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountReceived, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactInputSingleWithPoolParams memory poolParams = QuoteExactInputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amountIn: params.amountIn,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountReceived, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactInputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactInput(bytes memory path, uint256 amountIn)\n public\n view\n override\n returns (\n uint256 amountOut,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n\n // the outputs of prior swaps become the inputs to subsequent ones\n (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 initializedTicksCrossed,) = quoteExactInputSingle(\n QuoteExactInputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n fee: fee,\n amountIn: amountIn,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = initializedTicksCrossed;\n amountIn = _amountOut;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingleWithPool(QuoteExactOutputSingleWithPoolParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n int256 amount0;\n int256 amount1;\n uint256 amountReceived;\n\n bool zeroForOne = params.tokenIn < params.tokenOut;\n IUniswapV3Pool pool = IUniswapV3Pool(params.pool);\n\n uint256 amountOutCached = 0;\n // if no price limit has been specified, cache the output amount for comparison in the swap callback\n if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;\n\n QuoterMath.QuoteParams memory quoteParams = QuoterMath.QuoteParams({\n zeroForOne: zeroForOne,\n exactInput: true, // will be overridden\n fee: params.fee,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : params.sqrtPriceLimitX96\n });\n\n (amount0, amount1, sqrtPriceX96After, initializedTicksCrossed) =\n QuoterMath.quote(pool, -(params.amount.toInt256()), quoteParams);\n\n amountIn = amount0 > 0 ? uint256(amount0) : uint256(amount1);\n amountReceived = amount0 > 0 ? uint256(-amount1) : uint256(-amount0);\n\n // did we get the full amount?\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)\n public\n view\n override\n returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\n {\n address pool = getPool(params.tokenIn, params.tokenOut, params.fee);\n\n QuoteExactOutputSingleWithPoolParams memory poolParams = QuoteExactOutputSingleWithPoolParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n amount: params.amount,\n fee: params.fee,\n pool: pool,\n sqrtPriceLimitX96: 0\n });\n\n (amountIn, sqrtPriceX96After, initializedTicksCrossed,) = quoteExactOutputSingleWithPool(poolParams);\n }\n\n /// @inheritdoc IQuoter\n function quoteExactOutput(bytes memory path, uint256 amountOut)\n public\n view\n override\n returns (\n uint256 amountIn,\n uint160[] memory sqrtPriceX96AfterList,\n uint32[] memory initializedTicksCrossedList,\n uint256 gasEstimate\n )\n {\n sqrtPriceX96AfterList = new uint160[](path.numPools());\n initializedTicksCrossedList = new uint32[](path.numPools());\n\n uint256 i = 0;\n while (true) {\n (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();\n\n // the inputs of prior swaps become the outputs of subsequent ones\n (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed,) = quoteExactOutputSingle(\n QuoteExactOutputSingleParams({\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n amount: amountOut,\n fee: fee,\n sqrtPriceLimitX96: 0\n })\n );\n\n sqrtPriceX96AfterList[i] = _sqrtPriceX96After;\n initializedTicksCrossedList[i] = _initializedTicksCrossed;\n amountOut = _amountIn;\n i++;\n\n // decide whether to continue or terminate\n if (path.hasMultiplePools()) {\n path = path.skipToken();\n } else {\n return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, 0);\n }\n }\n }\n}" + } + }, + "settings": { + "optimizer": { + "enabled": true, + "runs": 200 + }, + "evmVersion": "paris", + "outputSelection": { + "*": { + "*": [ + "abi", + "evm.bytecode", + "evm.deployedBytecode", + "evm.methodIdentifiers", + "metadata", + "devdoc", + "userdoc", + "storageLayout", + "evm.gasEstimates" + ], + "": [ + "ast" + ] + } + }, + "metadata": { + "useLiteralContent": true + } + } +} \ No newline at end of file diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 5527d34af..36a763cfb 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -80,7 +80,7 @@ "@types/semver": "^7.3.9", "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^7.0.0", - "@uniswap/v4-core": "1.0.2", + "@uniswap/v4-core": "^1.0.2", "chai": "^4.3.4", "chai-as-promised": "^7.1.1", "chalk": "^4.1.1", diff --git a/packages/subgraph-pool/package.json b/packages/subgraph-pool/package.json index eb5175c9c..5a417486c 100644 --- a/packages/subgraph-pool/package.json +++ b/packages/subgraph-pool/package.json @@ -11,7 +11,7 @@ "remove-local": "graph remove --node http://localhost:8020/ teller-v2", "reset-local": "yarn remove-local && yarn create-local", "deploy-local": "graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 teller-v2", - "deploy_ormi": "bash -c 'source .env && graph deploy \"$0\" --node https://api.subgraph.migration.ormilabs.com/deploy --ipfs https://api.subgraph.migration.ormilabs.com/ipfs --deploy-key \"$ORMI_LABS_DEPLOY_KEY\"'", + "deploy_ormi": "bash -c 'source .env && graph deploy \"$0\" --node https://api.subgraph.migration.ormilabs.com/deploy --ipfs https://api.subgraph.migration.ormilabs.com/ipfs --deploy-key \"$ORMI_LABS_DEPLOY_KEY\"'", "test": "yarn graph test", "format": "eslint './src/**/*.ts' --fix", "ts-node": "ts-node --project ./scripts/tsconfig.json" diff --git a/packages/subgraph/package.json b/packages/subgraph/package.json index 93149e77c..7082f815b 100644 --- a/packages/subgraph/package.json +++ b/packages/subgraph/package.json @@ -4,9 +4,7 @@ "version": "0.4.21-18", "scripts": { "build": "graph codegen && graph build && graph codegen", - "handlebars": "bash -c 'yarn hbs -D ./config/$1.json ./src/subgraph.handlebars -o . -e yaml' _" , - - + "handlebars": "bash -c 'yarn hbs -D ./config/$1.json ./src/subgraph.handlebars -o . -e yaml' _", "deploy:prompt": "ts-node scripts/thegraph", "create-local": "graph create --node http://localhost:8020/ teller-v2", "remove-local": "graph remove --node http://localhost:8020/ teller-v2", diff --git a/yarn.lock b/yarn.lock index 1e542955e..e4dd7c075 100644 --- a/yarn.lock +++ b/yarn.lock @@ -59,15 +59,6 @@ __metadata: languageName: node linkType: hard -"@babel/code-frame@npm:7.12.11": - version: 7.12.11 - resolution: "@babel/code-frame@npm:7.12.11" - dependencies: - "@babel/highlight": ^7.10.4 - checksum: 3963eff3ebfb0e091c7e6f99596ef4b258683e4ba8a134e4e95f77afe85be5c931e184fff6435fb4885d12eba04a5e25532f7fbc292ca13b48e7da943474e2f3 - languageName: node - linkType: hard - "@babel/code-frame@npm:^7.0.0": version: 7.16.0 resolution: "@babel/code-frame@npm:7.16.0" @@ -84,7 +75,7 @@ __metadata: languageName: node linkType: hard -"@babel/highlight@npm:^7.10.4, @babel/highlight@npm:^7.16.0": +"@babel/highlight@npm:^7.16.0": version: 7.16.0 resolution: "@babel/highlight@npm:7.16.0" dependencies: @@ -95,52 +86,6 @@ __metadata: languageName: node linkType: hard -"@chainsafe/as-sha256@npm:^0.3.1": - version: 0.3.1 - resolution: "@chainsafe/as-sha256@npm:0.3.1" - checksum: 58ea733be1657b0e31dbf48b0dba862da0833df34a81c1460c7352f04ce90874f70003cbf34d0afb9e5e53a33ee2d63a261a8b12462be85b2ba0a6f7f13d6150 - languageName: node - linkType: hard - -"@chainsafe/persistent-merkle-tree@npm:^0.4.2": - version: 0.4.2 - resolution: "@chainsafe/persistent-merkle-tree@npm:0.4.2" - dependencies: - "@chainsafe/as-sha256": ^0.3.1 - checksum: f9cfcb2132a243992709715dbd28186ab48c7c0c696f29d30857693cca5526bf753974a505ef68ffd5623bbdbcaa10f9083f4dd40bf99eb6408e451cc26a1a9e - languageName: node - linkType: hard - -"@chainsafe/persistent-merkle-tree@npm:^0.5.0": - version: 0.5.0 - resolution: "@chainsafe/persistent-merkle-tree@npm:0.5.0" - dependencies: - "@chainsafe/as-sha256": ^0.3.1 - checksum: 2c67203da776c79cd3a6132e2d672fe132393b2e63dc71604e3134acc8c0ec25cc5e431051545939ea0f7c5ff2066fb806b9e5cab974ca085d046226a1671f7d - languageName: node - linkType: hard - -"@chainsafe/ssz@npm:^0.10.0": - version: 0.10.2 - resolution: "@chainsafe/ssz@npm:0.10.2" - dependencies: - "@chainsafe/as-sha256": ^0.3.1 - "@chainsafe/persistent-merkle-tree": ^0.5.0 - checksum: 6bb70cf741d0a19dd0b28b3f6f067b96fa39f556e2eefa6ac745b21db9c3b3a8393dc3cca8ff4a6ce065ed71ddc3fb1b2b390a92004b9d01067c26e2558e5503 - languageName: node - linkType: hard - -"@chainsafe/ssz@npm:^0.9.2": - version: 0.9.4 - resolution: "@chainsafe/ssz@npm:0.9.4" - dependencies: - "@chainsafe/as-sha256": ^0.3.1 - "@chainsafe/persistent-merkle-tree": ^0.4.2 - case: ^1.6.3 - checksum: c6eaedeae9e5618b3c666ff4507a27647f665a8dcf17d5ca86da4ed4788c5a93868f256d0005467d184fdf35ec03f323517ec2e55ec42492d769540a2ec396bc - languageName: node - linkType: hard - "@colors/colors@npm:1.5.0": version: 1.5.0 resolution: "@colors/colors@npm:1.5.0" @@ -157,147 +102,49 @@ __metadata: languageName: node linkType: hard -"@ensdomains/ens@npm:^0.4.4": - version: 0.4.5 - resolution: "@ensdomains/ens@npm:0.4.5" +"@eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0": + version: 4.9.1 + resolution: "@eslint-community/eslint-utils@npm:4.9.1" dependencies: - bluebird: ^3.5.2 - eth-ens-namehash: ^2.0.8 - solc: ^0.4.20 - testrpc: 0.0.1 - web3-utils: ^1.0.0-beta.31 - checksum: 3b4f6e34f3376f1b3cc60927d53d5951c4da0a9ff0f8856aaedba5a73bceccb7c08632bf6709b3bb9e43d6e83223d23928f574fc62dec12b2b1a692bcd3d45c6 + eslint-visitor-keys: ^3.4.3 + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + checksum: 0a27c2d676c4be6b329ebb5dd8f6c5ef5fae9a019ff575655306d72874bb26f3ab20e0b241a5f086464bb1f2511ca26a29ff6f80c1e2b0b02eca4686b4dfe1b5 languageName: node linkType: hard -"@ensdomains/resolver@npm:^0.2.4": - version: 0.2.4 - resolution: "@ensdomains/resolver@npm:0.2.4" - checksum: 3827a3430cc8935a0839dac9dafcfa6011c6f71af229ff91cbc6cdcbaa35d20c6dbb1a8a901cdb00e66428578ce1675bd6fe6901778b5d0d828321fbec9e0f7f +"@eslint-community/regexpp@npm:^4.10.0, @eslint-community/regexpp@npm:^4.6.1": + version: 4.12.2 + resolution: "@eslint-community/regexpp@npm:4.12.2" + checksum: 1770bc81f676a72f65c7200b5675ff7a349786521f30e66125faaf767fde1ba1c19c3790e16ba8508a62a3933afcfc806a893858b3b5906faf693d862b9e4120 languageName: node linkType: hard -"@eslint/eslintrc@npm:^0.4.3": - version: 0.4.3 - resolution: "@eslint/eslintrc@npm:0.4.3" +"@eslint/eslintrc@npm:^2.1.4": + version: 2.1.4 + resolution: "@eslint/eslintrc@npm:2.1.4" dependencies: ajv: ^6.12.4 - debug: ^4.1.1 - espree: ^7.3.0 - globals: ^13.9.0 - ignore: ^4.0.6 + debug: ^4.3.2 + espree: ^9.6.0 + globals: ^13.19.0 + ignore: ^5.2.0 import-fresh: ^3.2.1 - js-yaml: ^3.13.1 - minimatch: ^3.0.4 + js-yaml: ^4.1.0 + minimatch: ^3.1.2 strip-json-comments: ^3.1.1 - checksum: 03a7704150b868c318aab6a94d87a33d30dc2ec579d27374575014f06237ba1370ae11178db772f985ef680d469dc237e7b16a1c5d8edaaeb8c3733e7a95a6d3 - languageName: node - linkType: hard - -"@eth-optimism/hardhat-ovm@npm:^0.2.2": - version: 0.2.4 - resolution: "@eth-optimism/hardhat-ovm@npm:0.2.4" - dependencies: - node-fetch: ^2.6.1 - peerDependencies: - ethers: ^5.4.5 - hardhat: ^2.3.0 - checksum: 602acf597470ac7fb4b8adc03cdb55c0de0457945ce0bbcc23d4458b70072775a7dd32b9e84460feea8ef00d562b9e64986a1dd87c5a16c783b5dbfa435bcae5 - languageName: node - linkType: hard - -"@ethereum-waffle/chai@npm:^3.4.4": - version: 3.4.4 - resolution: "@ethereum-waffle/chai@npm:3.4.4" - dependencies: - "@ethereum-waffle/provider": ^3.4.4 - ethers: ^5.5.2 - checksum: b2b9b6b839c3f6b4abf8489fe50549e6fda07bd81ae8e4250b20d9a76ce4a729ef47c741364387b1d2dbc7fac14b46a5d6dcc4d404344b9cce5f9698ff012251 - languageName: node - linkType: hard - -"@ethereum-waffle/compiler@npm:^3.4.4": - version: 3.4.4 - resolution: "@ethereum-waffle/compiler@npm:3.4.4" - dependencies: - "@resolver-engine/imports": ^0.3.3 - "@resolver-engine/imports-fs": ^0.3.3 - "@typechain/ethers-v5": ^2.0.0 - "@types/mkdirp": ^0.5.2 - "@types/node-fetch": ^2.5.5 - ethers: ^5.0.1 - mkdirp: ^0.5.1 - node-fetch: ^2.6.1 - solc: ^0.6.3 - ts-generator: ^0.1.1 - typechain: ^3.0.0 - checksum: ebffca732969253934c1e8cca6cc1f12d6294f848d44e6595af81460bc3230bc69096d0965b9deb2c7eecd472a1d536d8cbe993f95bfc76fbbe2114ddbabff70 - languageName: node - linkType: hard - -"@ethereum-waffle/ens@npm:^3.4.4": - version: 3.4.4 - resolution: "@ethereum-waffle/ens@npm:3.4.4" - dependencies: - "@ensdomains/ens": ^0.4.4 - "@ensdomains/resolver": ^0.2.4 - ethers: ^5.5.2 - checksum: 71d93c09ef3ab89a46f05b9e2a06e129e2109d160c3a819e4bf3b4414fc4707e7fc646c87c1d82f9ba769dc1ac3c6f4934fd72499654fcfc9db4abf46c21d118 - languageName: node - linkType: hard - -"@ethereum-waffle/mock-contract@npm:^3.4.4": - version: 3.4.4 - resolution: "@ethereum-waffle/mock-contract@npm:3.4.4" - dependencies: - "@ethersproject/abi": ^5.5.0 - ethers: ^5.5.2 - checksum: 6e5c62b342e424cd1937f2f7eb424056ad143b238320880f378c0db61c6d694617f968687321a2f030d546aa5b4dde42681cbb419589d7f87452c82844a4488b + checksum: 10957c7592b20ca0089262d8c2a8accbad14b4f6507e35416c32ee6b4dbf9cad67dfb77096bbd405405e9ada2b107f3797fe94362e1c55e0b09d6e90dd149127 languageName: node linkType: hard -"@ethereum-waffle/provider@npm:^3.4.4": - version: 3.4.4 - resolution: "@ethereum-waffle/provider@npm:3.4.4" - dependencies: - "@ethereum-waffle/ens": ^3.4.4 - ethers: ^5.5.2 - ganache-core: ^2.13.2 - patch-package: ^6.2.2 - postinstall-postinstall: ^2.1.0 - checksum: 9e251d7b0198c22e337b18368e3893de766a821e818702dbef0e0d603bad550c6e3a29676cff11272bc82762833586ee9659593d957ec8759a8cc93c2b0f3d00 - languageName: node - linkType: hard - -"@ethereumjs/block@npm:^3.5.0, @ethereumjs/block@npm:^3.6.2, @ethereumjs/block@npm:^3.6.3": - version: 3.6.3 - resolution: "@ethereumjs/block@npm:3.6.3" - dependencies: - "@ethereumjs/common": ^2.6.5 - "@ethereumjs/tx": ^3.5.2 - ethereumjs-util: ^7.1.5 - merkle-patricia-tree: ^4.2.4 - checksum: d08c78134d15bc09c08b9a355ab736faa0f6b04ab87d2962e60df9c8bf977ebc68fe10aec6ca50bc2486532f489d7968fb5046defcd839b3b5ce28ca9dbce40f - languageName: node - linkType: hard - -"@ethereumjs/blockchain@npm:^5.5.3": - version: 5.5.3 - resolution: "@ethereumjs/blockchain@npm:5.5.3" - dependencies: - "@ethereumjs/block": ^3.6.2 - "@ethereumjs/common": ^2.6.4 - "@ethereumjs/ethash": ^1.1.0 - debug: ^4.3.3 - ethereumjs-util: ^7.1.5 - level-mem: ^5.0.1 - lru-cache: ^5.1.1 - semaphore-async-await: ^1.5.1 - checksum: eeefb4735ac06e6fe5ec5457eb9ac7aa26ced8651093d05067aee264f23704d79eacb1b2742e0651b73d2528aa8a9a40f3cc9e479f1837253c2dbb784a7a8e59 +"@eslint/js@npm:8.57.1": + version: 8.57.1 + resolution: "@eslint/js@npm:8.57.1" + checksum: 2afb77454c06e8316793d2e8e79a0154854d35e6782a1217da274ca60b5044d2c69d6091155234ed0551a1e408f86f09dd4ece02752c59568fa403e60611e880 languageName: node linkType: hard -"@ethereumjs/common@npm:^2.5.0, @ethereumjs/common@npm:^2.6.4, @ethereumjs/common@npm:^2.6.5": +"@ethereumjs/common@npm:^2.5.0, @ethereumjs/common@npm:^2.6.4": version: 2.6.5 resolution: "@ethereumjs/common@npm:2.6.5" dependencies: @@ -307,20 +154,25 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/ethash@npm:^1.1.0": - version: 1.1.0 - resolution: "@ethereumjs/ethash@npm:1.1.0" - dependencies: - "@ethereumjs/block": ^3.5.0 - "@types/levelup": ^4.3.0 - buffer-xor: ^2.0.1 - ethereumjs-util: ^7.1.1 - miller-rabin: ^4.0.0 - checksum: 152bc0850eeb0f2507383ca005418697b0a6a4487b120d7b3fadae4cb3b4781403c96c01f0c47149031431e518fb174c284ff38806b457f86f00c500eb213df3 +"@ethereumjs/rlp@npm:^4.0.1": + version: 4.0.1 + resolution: "@ethereumjs/rlp@npm:4.0.1" + bin: + rlp: bin/rlp + checksum: 30db19c78faa2b6ff27275ab767646929207bb207f903f09eb3e4c273ce2738b45f3c82169ddacd67468b4f063d8d96035f2bf36f02b6b7e4d928eefe2e3ecbc + languageName: node + linkType: hard + +"@ethereumjs/rlp@npm:^5.0.2": + version: 5.0.2 + resolution: "@ethereumjs/rlp@npm:5.0.2" + bin: + rlp: bin/rlp.cjs + checksum: b569061ddb1f4cf56a82f7a677c735ba37f9e94e2bbaf567404beb9e2da7aa1f595e72fc12a17c61f7aec67fd5448443efe542967c685a2fe0ffc435793dcbab languageName: node linkType: hard -"@ethereumjs/tx@npm:^3.3.2, @ethereumjs/tx@npm:^3.5.2": +"@ethereumjs/tx@npm:^3.3.2": version: 3.5.2 resolution: "@ethereumjs/tx@npm:3.5.2" dependencies: @@ -330,40 +182,24 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/vm@npm:^5.5.3": - version: 5.9.3 - resolution: "@ethereumjs/vm@npm:5.9.3" - dependencies: - "@ethereumjs/block": ^3.6.3 - "@ethereumjs/blockchain": ^5.5.3 - "@ethereumjs/common": ^2.6.5 - "@ethereumjs/tx": ^3.5.2 - async-eventemitter: ^0.2.4 - core-js-pure: ^3.0.1 - debug: ^4.3.3 - ethereumjs-util: ^7.1.5 - functional-red-black-tree: ^1.0.1 - mcl-wasm: ^0.7.1 - merkle-patricia-tree: ^4.2.4 - rustbn.js: ~0.2.0 - checksum: c5b4f85044342072ca009d8a26085f33764637492618522307a699a19123a3e18d36ff67126f8ab382cacf91cc94f5cabb8978e2ba9c5b2bf2ffdf20fe641e47 +"@ethereumjs/util@npm:^8.1.0": + version: 8.1.0 + resolution: "@ethereumjs/util@npm:8.1.0" + dependencies: + "@ethereumjs/rlp": ^4.0.1 + ethereum-cryptography: ^2.0.0 + micro-ftch: ^0.3.1 + checksum: 9ae5dee8f12b0faf81cd83f06a41560e79b0ba96a48262771d897a510ecae605eb6d84f687da001ab8ccffd50f612ae50f988ef76e6312c752897f462f3ac08d languageName: node linkType: hard -"@ethersproject/abi@npm:5.0.0-beta.153": - version: 5.0.0-beta.153 - resolution: "@ethersproject/abi@npm:5.0.0-beta.153" +"@ethereumjs/util@npm:^9.1.0": + version: 9.1.0 + resolution: "@ethereumjs/util@npm:9.1.0" dependencies: - "@ethersproject/address": ">=5.0.0-beta.128" - "@ethersproject/bignumber": ">=5.0.0-beta.130" - "@ethersproject/bytes": ">=5.0.0-beta.129" - "@ethersproject/constants": ">=5.0.0-beta.128" - "@ethersproject/hash": ">=5.0.0-beta.128" - "@ethersproject/keccak256": ">=5.0.0-beta.127" - "@ethersproject/logger": ">=5.0.0-beta.129" - "@ethersproject/properties": ">=5.0.0-beta.131" - "@ethersproject/strings": ">=5.0.0-beta.130" - checksum: 9f5c3c986a47c2bcc066e0ea1d8190be4358de6722d0eb75eaaacbc1f7610169691cc369085aa390bd88c731c6e539f309cb81face594feffac9336e369444c5 + "@ethereumjs/rlp": ^5.0.2 + ethereum-cryptography: ^2.2.1 + checksum: 594e009c3001ca1ca658b4ded01b38e72f5dd5dd76389efd90cb020de099176a3327685557df268161ac3144333cfe8abaae68cda8ae035d9cc82409d386d79a languageName: node linkType: hard @@ -401,6 +237,23 @@ __metadata: languageName: node linkType: hard +"@ethersproject/abi@npm:^5.0.9": + version: 5.8.0 + resolution: "@ethersproject/abi@npm:5.8.0" + dependencies: + "@ethersproject/address": ^5.8.0 + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/constants": ^5.8.0 + "@ethersproject/hash": ^5.8.0 + "@ethersproject/keccak256": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + "@ethersproject/strings": ^5.8.0 + checksum: cdab990d520fdbfd63d4a8829e78a2d2d2cc110dc3461895bd9014a49d3a9028c2005a11e2569c3fd620cb7780dcb5c71402630a8082a9ca5f85d4f8700d4549 + languageName: node + linkType: hard + "@ethersproject/abstract-provider@npm:5.7.0, @ethersproject/abstract-provider@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/abstract-provider@npm:5.7.0" @@ -431,6 +284,21 @@ __metadata: languageName: node linkType: hard +"@ethersproject/abstract-provider@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/abstract-provider@npm:5.8.0" + dependencies: + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/networks": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + "@ethersproject/transactions": ^5.8.0 + "@ethersproject/web": ^5.8.0 + checksum: 4fd00d770552af53be297c676f31d938f5dc44d73c24970036a11237a53f114cc1c551fd95937b9eca790f77087da1ed3ec54f97071df088d5861f575fd4f9be + languageName: node + linkType: hard + "@ethersproject/abstract-signer@npm:5.7.0, @ethersproject/abstract-signer@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/abstract-signer@npm:5.7.0" @@ -457,7 +325,20 @@ __metadata: languageName: node linkType: hard -"@ethersproject/address@npm:5.7.0, @ethersproject/address@npm:>=5.0.0-beta.128, @ethersproject/address@npm:^5.0.2, @ethersproject/address@npm:^5.7.0": +"@ethersproject/abstract-signer@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/abstract-signer@npm:5.8.0" + dependencies: + "@ethersproject/abstract-provider": ^5.8.0 + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + checksum: 3f7a98caf7c01e58da45d879c08449d1443bced36ac81938789c90d8f9ff86a1993655bae9805fc7b31a723b7bd7b4f1f768a9ec65dff032d0ebdc93133c14f3 + languageName: node + linkType: hard + +"@ethersproject/address@npm:5.7.0, @ethersproject/address@npm:^5.0.2, @ethersproject/address@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/address@npm:5.7.0" dependencies: @@ -483,6 +364,19 @@ __metadata: languageName: node linkType: hard +"@ethersproject/address@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/address@npm:5.8.0" + dependencies: + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/keccak256": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/rlp": ^5.8.0 + checksum: fa48e16403b656207f996ee7796f0978a146682f10f345b75aa382caa4a70fbfdc6ff585e9955e4779f4f15a31628929b665d288b895cea5df206c070266aea1 + languageName: node + linkType: hard + "@ethersproject/base64@npm:5.7.0, @ethersproject/base64@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/base64@npm:5.7.0" @@ -501,6 +395,15 @@ __metadata: languageName: node linkType: hard +"@ethersproject/base64@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/base64@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + checksum: f0c2136c99b2fd2f93b7e110958eacc5990e88274b1f38eb73d8eaa31bdead75fc0c4608dac23cb5718ae455b965de9dc5023446b96de62ef1fa945cbf212096 + languageName: node + linkType: hard + "@ethersproject/basex@npm:5.7.0, @ethersproject/basex@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/basex@npm:5.7.0" @@ -511,7 +414,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/bignumber@npm:5.7.0, @ethersproject/bignumber@npm:>=5.0.0-beta.130, @ethersproject/bignumber@npm:^5.7.0": +"@ethersproject/bignumber@npm:5.7.0, @ethersproject/bignumber@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/bignumber@npm:5.7.0" dependencies: @@ -533,7 +436,18 @@ __metadata: languageName: node linkType: hard -"@ethersproject/bytes@npm:5.7.0, @ethersproject/bytes@npm:>=5.0.0-beta.129, @ethersproject/bytes@npm:^5.7.0": +"@ethersproject/bignumber@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/bignumber@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + bn.js: ^5.2.1 + checksum: c87017f466b32d482e4b39370016cfc3edafc2feb89377011c54cd2e7dd011072ef4f275df59cd9fe080a187066082c1808b2682d97547c4fb9e6912331200c3 + languageName: node + linkType: hard + +"@ethersproject/bytes@npm:5.7.0, @ethersproject/bytes@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/bytes@npm:5.7.0" dependencies: @@ -551,7 +465,16 @@ __metadata: languageName: node linkType: hard -"@ethersproject/constants@npm:5.7.0, @ethersproject/constants@npm:>=5.0.0-beta.128, @ethersproject/constants@npm:^5.7.0": +"@ethersproject/bytes@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/bytes@npm:5.8.0" + dependencies: + "@ethersproject/logger": ^5.8.0 + checksum: 507e8ef1f1559590b4e78e3392a2b16090e96fb1091e0b08d3a8491df65976b313c29cdb412594454f68f9f04d5f77ea5a400b489d80a3e46a608156ef31b251 + languageName: node + linkType: hard + +"@ethersproject/constants@npm:5.7.0, @ethersproject/constants@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/constants@npm:5.7.0" dependencies: @@ -569,6 +492,15 @@ __metadata: languageName: node linkType: hard +"@ethersproject/constants@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/constants@npm:5.8.0" + dependencies: + "@ethersproject/bignumber": ^5.8.0 + checksum: 74830c44f4315a1058b905c73be7a9bb92850e45213cb28a957447b8a100f22a514f4500b0ea5ac7a995427cecef9918af39ae4e0e0ecf77aa4835b1ea5c3432 + languageName: node + linkType: hard + "@ethersproject/contracts@npm:5.7.0, @ethersproject/contracts@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/contracts@npm:5.7.0" @@ -587,7 +519,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/hash@npm:5.7.0, @ethersproject/hash@npm:>=5.0.0-beta.128, @ethersproject/hash@npm:^5.7.0": +"@ethersproject/hash@npm:5.7.0, @ethersproject/hash@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/hash@npm:5.7.0" dependencies: @@ -620,6 +552,23 @@ __metadata: languageName: node linkType: hard +"@ethersproject/hash@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/hash@npm:5.8.0" + dependencies: + "@ethersproject/abstract-signer": ^5.8.0 + "@ethersproject/address": ^5.8.0 + "@ethersproject/base64": ^5.8.0 + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/keccak256": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + "@ethersproject/strings": ^5.8.0 + checksum: e1feb47a98c631548b0f98ef0b1eb1b964bc643d5dea12a0eeb533165004cfcfe6f1d2bb32f31941f0b91e6a82212ad5c8577d6d465fba62c38fc0c410941feb + languageName: node + linkType: hard + "@ethersproject/hdnode@npm:5.7.0, @ethersproject/hdnode@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/hdnode@npm:5.7.0" @@ -661,7 +610,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/keccak256@npm:5.7.0, @ethersproject/keccak256@npm:>=5.0.0-beta.127, @ethersproject/keccak256@npm:^5.7.0": +"@ethersproject/keccak256@npm:5.7.0, @ethersproject/keccak256@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/keccak256@npm:5.7.0" dependencies: @@ -681,7 +630,17 @@ __metadata: languageName: node linkType: hard -"@ethersproject/logger@npm:5.7.0, @ethersproject/logger@npm:>=5.0.0-beta.129, @ethersproject/logger@npm:^5.7.0": +"@ethersproject/keccak256@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/keccak256@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + js-sha3: 0.8.0 + checksum: af3621d2b18af6c8f5181dacad91e1f6da4e8a6065668b20e4c24684bdb130b31e45e0d4dbaed86d4f1314d01358aa119f05be541b696e455424c47849d81913 + languageName: node + linkType: hard + +"@ethersproject/logger@npm:5.7.0, @ethersproject/logger@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/logger@npm:5.7.0" checksum: 075ab2f605f1fd0813f2e39c3308f77b44a67732b36e712d9bc085f22a84aac4da4f71b39bee50fe78da3e1c812673fadc41180c9970fe5e486e91ea17befe0d @@ -695,6 +654,13 @@ __metadata: languageName: node linkType: hard +"@ethersproject/logger@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/logger@npm:5.8.0" + checksum: 6249885a7fd4a5806e4c8700b76ffcc8f1ff00d71f31aa717716a89fa6b391de19fbb0cb5ae2560b9f57ec0c2e8e0a11ebc2099124c73d3b42bc58e3eedc41d1 + languageName: node + linkType: hard + "@ethersproject/networks@npm:5.7.1, @ethersproject/networks@npm:^5.7.0": version: 5.7.1 resolution: "@ethersproject/networks@npm:5.7.1" @@ -713,6 +679,15 @@ __metadata: languageName: node linkType: hard +"@ethersproject/networks@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/networks@npm:5.8.0" + dependencies: + "@ethersproject/logger": ^5.8.0 + checksum: b1d43fdab13e32be74b5547968c7e54786915a1c3543025c628f634872038750171bef15db0cf42a27e568175b185ac9c185a9aae8f93839452942c5a867c908 + languageName: node + linkType: hard + "@ethersproject/pbkdf2@npm:5.7.0, @ethersproject/pbkdf2@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/pbkdf2@npm:5.7.0" @@ -723,7 +698,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/properties@npm:5.7.0, @ethersproject/properties@npm:>=5.0.0-beta.131, @ethersproject/properties@npm:^5.7.0": +"@ethersproject/properties@npm:5.7.0, @ethersproject/properties@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/properties@npm:5.7.0" dependencies: @@ -741,7 +716,16 @@ __metadata: languageName: node linkType: hard -"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.7.1, @ethersproject/providers@npm:^5.7.2": +"@ethersproject/properties@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/properties@npm:5.8.0" + dependencies: + "@ethersproject/logger": ^5.8.0 + checksum: 2bb0369a3c25a7c1999e990f73a9db149a5e514af253e3945c7728eaea5d864144da6a81661c0c414b97be75db7fb15c34f719169a3adb09e585a3286ea78b9c + languageName: node + linkType: hard + +"@ethersproject/providers@npm:5.7.2, @ethersproject/providers@npm:^5.7.2": version: 5.7.2 resolution: "@ethersproject/providers@npm:5.7.2" dependencies: @@ -799,6 +783,16 @@ __metadata: languageName: node linkType: hard +"@ethersproject/rlp@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/rlp@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + checksum: 9d6f646072b3dd61de993210447d35744a851d24d4fe6262856e372f47a1e9d90976031a9fa28c503b1a4f39dd5ab7c20fc9b651b10507a09b40a33cb04a19f1 + languageName: node + linkType: hard + "@ethersproject/sha2@npm:5.7.0, @ethersproject/sha2@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/sha2@npm:5.7.0" @@ -838,6 +832,20 @@ __metadata: languageName: node linkType: hard +"@ethersproject/signing-key@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/signing-key@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + bn.js: ^5.2.1 + elliptic: 6.6.1 + hash.js: 1.1.7 + checksum: 8c07741bc8275568130d97da5d37535c813c842240d0b3409d5e057321595eaf65660c207abdee62e2d7ba225d9b82f0b711ac0324c8c9ceb09a815b231b9f55 + languageName: node + linkType: hard + "@ethersproject/solidity@npm:5.7.0, @ethersproject/solidity@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/solidity@npm:5.7.0" @@ -852,7 +860,7 @@ __metadata: languageName: node linkType: hard -"@ethersproject/strings@npm:5.7.0, @ethersproject/strings@npm:>=5.0.0-beta.130, @ethersproject/strings@npm:^5.7.0": +"@ethersproject/strings@npm:5.7.0, @ethersproject/strings@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/strings@npm:5.7.0" dependencies: @@ -874,7 +882,18 @@ __metadata: languageName: node linkType: hard -"@ethersproject/transactions@npm:5.7.0, @ethersproject/transactions@npm:^5.0.0-beta.135, @ethersproject/transactions@npm:^5.6.2, @ethersproject/transactions@npm:^5.7.0": +"@ethersproject/strings@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/strings@npm:5.8.0" + dependencies: + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/constants": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + checksum: 997396cf1b183ae66ebfd97b9f98fd50415489f9246875e7769e57270ffa1bffbb62f01430eaac3a0c9cb284e122040949efe632a0221012ee47de252a44a483 + languageName: node + linkType: hard + +"@ethersproject/transactions@npm:5.7.0, @ethersproject/transactions@npm:^5.6.2, @ethersproject/transactions@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/transactions@npm:5.7.0" dependencies: @@ -908,6 +927,23 @@ __metadata: languageName: node linkType: hard +"@ethersproject/transactions@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/transactions@npm:5.8.0" + dependencies: + "@ethersproject/address": ^5.8.0 + "@ethersproject/bignumber": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/constants": ^5.8.0 + "@ethersproject/keccak256": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + "@ethersproject/rlp": ^5.8.0 + "@ethersproject/signing-key": ^5.8.0 + checksum: e867516ccc692c3642bfbd34eab6d2acecabb3b964d8e1cced8e450ec4fa490bcf2513efb6252637bc3157ecd5e0250dadd1a08d3ec3150c14478b9ec7715570 + languageName: node + linkType: hard + "@ethersproject/units@npm:5.7.0": version: 5.7.0 resolution: "@ethersproject/units@npm:5.7.0" @@ -968,6 +1004,19 @@ __metadata: languageName: node linkType: hard +"@ethersproject/web@npm:^5.8.0": + version: 5.8.0 + resolution: "@ethersproject/web@npm:5.8.0" + dependencies: + "@ethersproject/base64": ^5.8.0 + "@ethersproject/bytes": ^5.8.0 + "@ethersproject/logger": ^5.8.0 + "@ethersproject/properties": ^5.8.0 + "@ethersproject/strings": ^5.8.0 + checksum: d8ca89bde8777ed1eec81527f8a989b939b4625b2f6c275eea90031637a802ad68bf46911fdd43c5e84ea2962b8a3cb4801ab51f5393ae401a163c17c774123f + languageName: node + linkType: hard + "@ethersproject/wordlists@npm:5.7.0, @ethersproject/wordlists@npm:^5.7.0": version: 5.7.0 resolution: "@ethersproject/wordlists@npm:5.7.0" @@ -1071,21 +1120,28 @@ __metadata: languageName: node linkType: hard -"@humanwhocodes/config-array@npm:^0.5.0": - version: 0.5.0 - resolution: "@humanwhocodes/config-array@npm:0.5.0" +"@humanwhocodes/config-array@npm:^0.13.0": + version: 0.13.0 + resolution: "@humanwhocodes/config-array@npm:0.13.0" dependencies: - "@humanwhocodes/object-schema": ^1.2.0 - debug: ^4.1.1 - minimatch: ^3.0.4 - checksum: 44ee6a9f05d93dd9d5935a006b17572328ba9caff8002442f601736cbda79c580cc0f5a49ce9eb88fbacc5c3a6b62098357c2e95326cd17bb9f1a6c61d6e95e7 + "@humanwhocodes/object-schema": ^2.0.3 + debug: ^4.3.1 + minimatch: ^3.0.5 + checksum: eae69ff9134025dd2924f0b430eb324981494be26f0fddd267a33c28711c4db643242cf9fddf7dadb9d16c96b54b2d2c073e60a56477df86e0173149313bd5d6 languageName: node linkType: hard -"@humanwhocodes/object-schema@npm:^1.2.0": - version: 1.2.0 - resolution: "@humanwhocodes/object-schema@npm:1.2.0" - checksum: 40b75480376de8104d65f7c44a7dd76d30fb57823ca8ba3a3239b2b568323be894d93440578a72fd8e5e2cc3df3577ce0d2f0fe308b990dd51cf35392bf3c9a2 +"@humanwhocodes/module-importer@npm:^1.0.1": + version: 1.0.1 + resolution: "@humanwhocodes/module-importer@npm:1.0.1" + checksum: 0fd22007db8034a2cdf2c764b140d37d9020bbfce8a49d3ec5c05290e77d4b0263b1b972b752df8c89e5eaa94073408f2b7d977aed131faf6cf396ebb5d7fb61 + languageName: node + linkType: hard + +"@humanwhocodes/object-schema@npm:^2.0.3": + version: 2.0.3 + resolution: "@humanwhocodes/object-schema@npm:2.0.3" + checksum: d3b78f6c5831888c6ecc899df0d03bcc25d46f3ad26a11d7ea52944dc36a35ef543fad965322174238d677a43d5c694434f6607532cff7077062513ad7022631 languageName: node linkType: hard @@ -1481,19 +1537,6 @@ __metadata: languageName: node linkType: hard -"@metamask/eth-sig-util@npm:^4.0.0": - version: 4.0.1 - resolution: "@metamask/eth-sig-util@npm:4.0.1" - dependencies: - ethereumjs-abi: ^0.6.8 - ethereumjs-util: ^6.2.1 - ethjs-util: ^0.1.6 - tweetnacl: ^1.0.3 - tweetnacl-util: ^0.15.1 - checksum: 740df4c92a1282e6be4c00c86c1a8ccfb93e767596e43f6da895aa5bab4a28fc3c2209f0327db34924a4a1e9db72bc4d3dddfcfc45cca0b218c9ccbf7d1b1445 - languageName: node - linkType: hard - "@morgan-stanley/ts-mocking-bird@npm:^0.6.2": version: 0.6.4 resolution: "@morgan-stanley/ts-mocking-bird@npm:0.6.4" @@ -1520,6 +1563,15 @@ __metadata: languageName: node linkType: hard +"@noble/curves@npm:1.4.2, @noble/curves@npm:~1.4.0": + version: 1.4.2 + resolution: "@noble/curves@npm:1.4.2" + dependencies: + "@noble/hashes": 1.4.0 + checksum: c475a83c4263e2c970eaba728895b9b5d67e0ca880651e9c6e3efdc5f6a4f07ceb5b043bf71c399fc80fada0b8706e69d0772bffdd7b9de2483b988973a34cba + languageName: node + linkType: hard + "@noble/curves@npm:1.9.2, @noble/curves@npm:^1.6.0, @noble/curves@npm:^1.9.1, @noble/curves@npm:~1.9.0": version: 1.9.2 resolution: "@noble/curves@npm:1.9.2" @@ -1529,6 +1581,15 @@ __metadata: languageName: node linkType: hard +"@noble/curves@npm:~1.8.1": + version: 1.8.2 + resolution: "@noble/curves@npm:1.8.2" + dependencies: + "@noble/hashes": 1.7.2 + checksum: f26fd77b4d78fe26dba2754cbcaddee5da23a711a0c9778ee57764eb0084282d97659d9b0a760718f42493adf68665dbffdca9d6213950f03f079d09c465c096 + languageName: node + linkType: hard + "@noble/hashes@npm:1.1.2": version: 1.1.2 resolution: "@noble/hashes@npm:1.1.2" @@ -1536,6 +1597,20 @@ __metadata: languageName: node linkType: hard +"@noble/hashes@npm:1.4.0, @noble/hashes@npm:~1.4.0": + version: 1.4.0 + resolution: "@noble/hashes@npm:1.4.0" + checksum: 8ba816ae26c90764b8c42493eea383716396096c5f7ba6bea559993194f49d80a73c081f315f4c367e51bd2d5891700bcdfa816b421d24ab45b41cb03e4f3342 + languageName: node + linkType: hard + +"@noble/hashes@npm:1.7.2, @noble/hashes@npm:~1.7.1": + version: 1.7.2 + resolution: "@noble/hashes@npm:1.7.2" + checksum: f9e3c2e62c2850073f8d6ac30cc33b03a25cae859eb2209b33ae90ed3d1e003cb2a1ddacd2aacd6b7c98a5ad70795a234ccce04b0526657cd8020ce4ffdb491f + languageName: node + linkType: hard + "@noble/hashes@npm:1.8.0, @noble/hashes@npm:^1.8.0, @noble/hashes@npm:~1.8.0": version: 1.8.0 resolution: "@noble/hashes@npm:1.8.0" @@ -1581,7 +1656,7 @@ __metadata: languageName: node linkType: hard -"@nodelib/fs.walk@npm:^1.2.3": +"@nodelib/fs.walk@npm:^1.2.3, @nodelib/fs.walk@npm:^1.2.8": version: 1.2.8 resolution: "@nodelib/fs.walk@npm:1.2.8" dependencies: @@ -1591,161 +1666,67 @@ __metadata: languageName: node linkType: hard -"@nomicfoundation/ethereumjs-block@npm:5.0.1": - version: 5.0.1 - resolution: "@nomicfoundation/ethereumjs-block@npm:5.0.1" - dependencies: - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-trie": 6.0.1 - "@nomicfoundation/ethereumjs-tx": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - ethereum-cryptography: 0.1.3 - ethers: ^5.7.1 - checksum: 02591bc9ba02b56edc5faf75a7991d6b9430bd98542864f2f6ab202f0f4aed09be156fdba60948375beb10e524ffa4e461475edc8a15b3098b1c58ff59a0137e - languageName: node - linkType: hard - -"@nomicfoundation/ethereumjs-blockchain@npm:7.0.1": - version: 7.0.1 - resolution: "@nomicfoundation/ethereumjs-blockchain@npm:7.0.1" - dependencies: - "@nomicfoundation/ethereumjs-block": 5.0.1 - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-ethash": 3.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-trie": 6.0.1 - "@nomicfoundation/ethereumjs-tx": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - abstract-level: ^1.0.3 - debug: ^4.3.3 - ethereum-cryptography: 0.1.3 - level: ^8.0.0 - lru-cache: ^5.1.1 - memory-level: ^1.0.0 - checksum: 8b7a4e3613c2abbf59e92a927cb074d1df8640fbf6a0ec4be7fcb5ecaead1310ebbe3a41613c027253742f6dccca6eaeee8dde0a38315558de156313d0c8f313 - languageName: node - linkType: hard - -"@nomicfoundation/ethereumjs-common@npm:4.0.1": - version: 4.0.1 - resolution: "@nomicfoundation/ethereumjs-common@npm:4.0.1" - dependencies: - "@nomicfoundation/ethereumjs-util": 9.0.1 - crc-32: ^1.2.0 - checksum: af5b599bcc07430b57017e516b0bad70af04e812b970be9bfae0c1d3433ab26656b3d1db71717b3b0fb38a889db2b93071b45adc1857000e7cd58a99a8e29495 - languageName: node - linkType: hard - -"@nomicfoundation/ethereumjs-ethash@npm:3.0.1": - version: 3.0.1 - resolution: "@nomicfoundation/ethereumjs-ethash@npm:3.0.1" - dependencies: - "@nomicfoundation/ethereumjs-block": 5.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - abstract-level: ^1.0.3 - bigint-crypto-utils: ^3.0.23 - ethereum-cryptography: 0.1.3 - checksum: beeec9788a9ed57020ee47271447715bdc0a98990a0bd0e9d598c6de74ade836db17c0590275e6aab12fa9b0fbd81f1d02e3cdf1fb8497583cec693ec3ed6aed +"@nomicfoundation/edr-darwin-arm64@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-darwin-arm64@npm:0.12.0-next.23" + checksum: 2cb6edbd58ed730f0ec1c56a468ec1cd9e5359850eb09041d55f3269b7e81e8f3bd0eb8c619bc94738761d6c07b758710863ef0631d5a5366ce1823470d62e26 languageName: node linkType: hard -"@nomicfoundation/ethereumjs-evm@npm:2.0.1": - version: 2.0.1 - resolution: "@nomicfoundation/ethereumjs-evm@npm:2.0.1" - dependencies: - "@ethersproject/providers": ^5.7.1 - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-tx": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - debug: ^4.3.3 - ethereum-cryptography: 0.1.3 - mcl-wasm: ^0.7.1 - rustbn.js: ~0.2.0 - checksum: 0aa2e1460e1c311506fd3bf9d03602c7c3a5e03f352173a55a274a9cc1840bd774692d1c4e5c6e82a7eee015a7cf1585f1c5be02cfdf54cc2a771421820e3f84 +"@nomicfoundation/edr-darwin-x64@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-darwin-x64@npm:0.12.0-next.23" + checksum: 5f880492c4202fdd32c986548e42412bb291e65e6f8b9b4b35d2a79e011ed0a1294fed55ec57e2678350a9e8818148f032809d17d9a7d62300d5d7d7dc310789 languageName: node linkType: hard -"@nomicfoundation/ethereumjs-rlp@npm:5.0.1": - version: 5.0.1 - resolution: "@nomicfoundation/ethereumjs-rlp@npm:5.0.1" - bin: - rlp: bin/rlp - checksum: 5a51d2cf92b84e50ce516cbdadff5d39cb4c6b71335e92eaf447dfb7d88f5499d78d599024b9252efd7ba99495de36f4d983cec6a89e77db286db691fc6328f7 +"@nomicfoundation/edr-linux-arm64-gnu@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-linux-arm64-gnu@npm:0.12.0-next.23" + checksum: 12330a28a5aa9321280fb14ead133368d11bbfab690bac14ccec794044c7ccd3f149cb3bc8a7a9b6907c200b454e4b6d2243fa8657b2c6c71ce0da13748ef33e languageName: node linkType: hard -"@nomicfoundation/ethereumjs-statemanager@npm:2.0.1": - version: 2.0.1 - resolution: "@nomicfoundation/ethereumjs-statemanager@npm:2.0.1" - dependencies: - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - debug: ^4.3.3 - ethereum-cryptography: 0.1.3 - ethers: ^5.7.1 - js-sdsl: ^4.1.4 - checksum: 157b503fa3e45a3695ba2eba5b089b56719f7790274edd09c95bb0d223570820127f6a2cbfcb14f2d9d876d1440ea4dccb04a4922fa9e9e34b416fddd6517c20 +"@nomicfoundation/edr-linux-arm64-musl@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-linux-arm64-musl@npm:0.12.0-next.23" + checksum: 1bf5dd4a96706a2db2c42b99b204ecbcde5876ebfcb941a20ab3bd2a6f978e3e94eac678f3e503afa6710518e59dc8550c29931dba6dadc74342c26f3f625d9b languageName: node linkType: hard -"@nomicfoundation/ethereumjs-trie@npm:6.0.1": - version: 6.0.1 - resolution: "@nomicfoundation/ethereumjs-trie@npm:6.0.1" - dependencies: - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - "@types/readable-stream": ^2.3.13 - ethereum-cryptography: 0.1.3 - readable-stream: ^3.6.0 - checksum: 7001c3204120fd4baba673b4bb52015594f5ad28311f24574cd16f38c015ef87ed51188d6f46d6362ffb9da589359a9e0f99e6068ef7a2f61cb66213e2f493d7 +"@nomicfoundation/edr-linux-x64-gnu@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-linux-x64-gnu@npm:0.12.0-next.23" + checksum: 48c1a4749df67d95424fdb2c098b7a8fc41a982b544fd1932ae31557ec03b38731942ecd8ab03b77a628ca1cf55160861f736140da34490020daf85ba23f362d languageName: node linkType: hard -"@nomicfoundation/ethereumjs-tx@npm:5.0.1": - version: 5.0.1 - resolution: "@nomicfoundation/ethereumjs-tx@npm:5.0.1" - dependencies: - "@chainsafe/ssz": ^0.9.2 - "@ethersproject/providers": ^5.7.2 - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - ethereum-cryptography: 0.1.3 - checksum: aa3829e4a43f5e10cfd66b87eacb3e737ba98f5e3755a3e6a4ccfbc257dbf10d926838cc3acb8fef8afa3362a023b7fd11b53e6ba53f94bb09c345f083cd29a8 +"@nomicfoundation/edr-linux-x64-musl@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-linux-x64-musl@npm:0.12.0-next.23" + checksum: 95b077d4a5abf79077a86801ea56efe3c50419705db4c8ee422b51c6b7ee819177f3b272b2257abab539e34b9ea76dbdc7f158eb8f6de1404e81507c4d64bb64 languageName: node linkType: hard -"@nomicfoundation/ethereumjs-util@npm:9.0.1": - version: 9.0.1 - resolution: "@nomicfoundation/ethereumjs-util@npm:9.0.1" - dependencies: - "@chainsafe/ssz": ^0.10.0 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - ethereum-cryptography: 0.1.3 - checksum: 5f8a50a25c68c974b717f36ad0a5828b786ce1aaea3c874663c2014593fa387de5ad5c8cea35e94379df306dbd1a58c55b310779fd82197dcb993d5dbd4de7a1 +"@nomicfoundation/edr-win32-x64-msvc@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr-win32-x64-msvc@npm:0.12.0-next.23" + checksum: 0fb49203b7aa16ba536f735515d3f7db78a8d9d50f8748ff033a7e924f94a59fb7a5a7263babf89bb1bb0ab2f13505449c496d66581f54d5f27d92c90476bc32 languageName: node linkType: hard -"@nomicfoundation/ethereumjs-vm@npm:7.0.1": - version: 7.0.1 - resolution: "@nomicfoundation/ethereumjs-vm@npm:7.0.1" +"@nomicfoundation/edr@npm:0.12.0-next.23": + version: 0.12.0-next.23 + resolution: "@nomicfoundation/edr@npm:0.12.0-next.23" dependencies: - "@nomicfoundation/ethereumjs-block": 5.0.1 - "@nomicfoundation/ethereumjs-blockchain": 7.0.1 - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-evm": 2.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-statemanager": 2.0.1 - "@nomicfoundation/ethereumjs-trie": 6.0.1 - "@nomicfoundation/ethereumjs-tx": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - debug: ^4.3.3 - ethereum-cryptography: 0.1.3 - mcl-wasm: ^0.7.1 - rustbn.js: ~0.2.0 - checksum: 0f637316322744140d6f75d894c21b8055e27a94c72dd8ae9b0b9b93c0d54d7f30fa2aaf909e802e183a3f1020b4aa6a8178dedb823a4ce70a227ac7b432f8c1 + "@nomicfoundation/edr-darwin-arm64": 0.12.0-next.23 + "@nomicfoundation/edr-darwin-x64": 0.12.0-next.23 + "@nomicfoundation/edr-linux-arm64-gnu": 0.12.0-next.23 + "@nomicfoundation/edr-linux-arm64-musl": 0.12.0-next.23 + "@nomicfoundation/edr-linux-x64-gnu": 0.12.0-next.23 + "@nomicfoundation/edr-linux-x64-musl": 0.12.0-next.23 + "@nomicfoundation/edr-win32-x64-msvc": 0.12.0-next.23 + checksum: ebbfdb52e41f4dba0f3c185b3f62fc479813a8eafb34a07cc91af5a0b7d016f91b7877e5b642739e28fd24c317d7e15c5250c29a6a07997cbc7b97ecb463d37e languageName: node linkType: hard @@ -2147,6 +2128,13 @@ __metadata: languageName: node linkType: hard +"@pkgr/core@npm:^0.2.9": + version: 0.2.9 + resolution: "@pkgr/core@npm:0.2.9" + checksum: bb2fb86977d63f836f8f5b09015d74e6af6488f7a411dcd2bfdca79d76b5a681a9112f41c45bdf88a9069f049718efc6f3900d7f1de66a2ec966068308ae517f + languageName: node + linkType: hard + "@protobufjs/aspromise@npm:^1.1.1, @protobufjs/aspromise@npm:^1.1.2": version: 1.1.2 resolution: "@protobufjs/aspromise@npm:1.1.2" @@ -2227,51 +2215,6 @@ __metadata: languageName: node linkType: hard -"@resolver-engine/core@npm:^0.3.3": - version: 0.3.3 - resolution: "@resolver-engine/core@npm:0.3.3" - dependencies: - debug: ^3.1.0 - is-url: ^1.2.4 - request: ^2.85.0 - checksum: e5ac586da2aeb7e384f6841821e528771fca533bf5cf38d7fd0851733bd9b70939e960459f2b841534ecdca6507c9aff71bd317f7481137d7b1d2e87ba15978a - languageName: node - linkType: hard - -"@resolver-engine/fs@npm:^0.3.3": - version: 0.3.3 - resolution: "@resolver-engine/fs@npm:0.3.3" - dependencies: - "@resolver-engine/core": ^0.3.3 - debug: ^3.1.0 - checksum: 734577b7864c3aceaaa80b4b74c252d92fb14a6f3c46dfc0a2d4658288dce1b38797578dd6a4ecbde88cbc4a366e8bdbc46451e282cb25dde8479548453c37a3 - languageName: node - linkType: hard - -"@resolver-engine/imports-fs@npm:^0.3.3": - version: 0.3.3 - resolution: "@resolver-engine/imports-fs@npm:0.3.3" - dependencies: - "@resolver-engine/fs": ^0.3.3 - "@resolver-engine/imports": ^0.3.3 - debug: ^3.1.0 - checksum: d24778788959f8a201bda0a91527cd1703dfbbf3675fd16bd3891046e3f12378be73233bb9d4da19c7247488be38daeab2bdf800317f70553a16fb62208ba2c7 - languageName: node - linkType: hard - -"@resolver-engine/imports@npm:^0.3.3": - version: 0.3.3 - resolution: "@resolver-engine/imports@npm:0.3.3" - dependencies: - "@resolver-engine/core": ^0.3.3 - debug: ^3.1.0 - hosted-git-info: ^2.6.0 - path-browserify: ^1.0.0 - url: ^0.11.0 - checksum: 690cf550fd0608e849fcb9c20a08479ce405173f8d0b09141a5bd140c4ae7c887ebcb0532c4ca64b5c1d3039fe77cc94172b7afb51c1a8fe7722475c429e6944 - languageName: node - linkType: hard - "@safe-global/protocol-kit@npm:6.1.0": version: 6.1.0 resolution: "@safe-global/protocol-kit@npm:6.1.0" @@ -2322,10 +2265,10 @@ __metadata: version: 0.0.0-use.local resolution: "@scaffold-eth/typescript@workspace:." dependencies: - eslint: ^7.32.0 + eslint: ^8.56.0 husky: ^8.0.1 mustache: ^4.2.0 - prettier: ^2.4.1 + prettier: ^3.2.0 shx: ^0.3.3 languageName: unknown linkType: soft @@ -2337,6 +2280,13 @@ __metadata: languageName: node linkType: hard +"@scure/base@npm:~1.1.6": + version: 1.1.9 + resolution: "@scure/base@npm:1.1.9" + checksum: 120820a37dfe9dfe4cab2b7b7460552d08e67dee8057ed5354eb68d8e3440890ae983ce3bee957d2b45684950b454a2b6d71d5ee77c1fd3fddc022e2a510337f + languageName: node + linkType: hard + "@scure/base@npm:~1.2.5": version: 1.2.6 resolution: "@scure/base@npm:1.2.6" @@ -2355,6 +2305,17 @@ __metadata: languageName: node linkType: hard +"@scure/bip32@npm:1.4.0": + version: 1.4.0 + resolution: "@scure/bip32@npm:1.4.0" + dependencies: + "@noble/curves": ~1.4.0 + "@noble/hashes": ~1.4.0 + "@scure/base": ~1.1.6 + checksum: eff491651cbf2bea8784936de75af5fc020fc1bbb9bcb26b2cfeefbd1fb2440ebfaf30c0733ca11c0ae1e272a2ef4c3c34ba5c9fb3e1091c3285a4272045b0c6 + languageName: node + linkType: hard + "@scure/bip32@npm:1.7.0, @scure/bip32@npm:^1.7.0": version: 1.7.0 resolution: "@scure/bip32@npm:1.7.0" @@ -2376,6 +2337,16 @@ __metadata: languageName: node linkType: hard +"@scure/bip39@npm:1.3.0": + version: 1.3.0 + resolution: "@scure/bip39@npm:1.3.0" + dependencies: + "@noble/hashes": ~1.4.0 + "@scure/base": ~1.1.6 + checksum: dbb0b27df753eb6c6380010b25cc9a9ea31f9cb08864fc51e69e5880ff7e2b8f85b72caea1f1f28af165e83b72c48dd38617e43fc632779d025b50ba32ea759e + languageName: node + linkType: hard + "@scure/bip39@npm:1.6.0, @scure/bip39@npm:^1.6.0": version: 1.6.0 resolution: "@scure/bip39@npm:1.6.0" @@ -2468,13 +2439,6 @@ __metadata: languageName: node linkType: hard -"@sindresorhus/is@npm:^0.14.0": - version: 0.14.0 - resolution: "@sindresorhus/is@npm:0.14.0" - checksum: 971e0441dd44ba3909b467219a5e242da0fc584048db5324cfb8048148fa8dcc9d44d71e3948972c4f6121d24e5da402ef191420d1266a95f713bb6d6e59c98a - languageName: node - linkType: hard - "@sindresorhus/is@npm:^4.0.0, @sindresorhus/is@npm:^4.6.0": version: 4.6.0 resolution: "@sindresorhus/is@npm:4.6.0" @@ -2482,7 +2446,7 @@ __metadata: languageName: node linkType: hard -"@solidity-parser/parser@npm:^0.14.0, @solidity-parser/parser@npm:^0.14.1, @solidity-parser/parser@npm:^0.14.3": +"@solidity-parser/parser@npm:^0.14.0, @solidity-parser/parser@npm:^0.14.1": version: 0.14.5 resolution: "@solidity-parser/parser@npm:0.14.5" dependencies: @@ -2491,12 +2455,10 @@ __metadata: languageName: node linkType: hard -"@szmarczak/http-timer@npm:^1.1.2": - version: 1.1.2 - resolution: "@szmarczak/http-timer@npm:1.1.2" - dependencies: - defer-to-connect: ^1.0.1 - checksum: 4d9158061c5f397c57b4988cde33a163244e4f02df16364f103971957a32886beb104d6180902cbe8b38cb940e234d9f98a4e486200deca621923f62f50a06fe +"@solidity-parser/parser@npm:^0.20.1": + version: 0.20.2 + resolution: "@solidity-parser/parser@npm:0.20.2" + checksum: 5623e9b5863d59aab50f0fc98fe81a2b693e64feb29e2cf011a826d0e89374bbb6dfaf3fce48ac5c462251c792042f47805ba2004993182b717314e7d7292cd4 languageName: node linkType: hard @@ -2536,21 +2498,21 @@ __metadata: "@types/prompts": ^2.4.4 "@types/semver": ^7.5.0 "@types/uuid": ^9.0.2 - "@typescript-eslint/eslint-plugin": ^5.5.0 - "@typescript-eslint/parser": ^5.5.0 + "@typescript-eslint/eslint-plugin": ^7.0.0 + "@typescript-eslint/parser": ^7.0.0 assemblyscript: ^0.27.1 async-mutex: ^0.4.0 axios: ^1.4.0 cleaners: ^0.3.16 cli-progress: ^3.12.0 - eslint: ^7.32.0 + eslint: ^8.56.0 eslint-config-prettier: ^8.3.0 eslint-config-standard-kit: 0.15.1 eslint-plugin-import: ^2.25.2 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^4.0.0 + eslint-plugin-prettier: ^5.0.0 eslint-plugin-simple-import-sort: ^7.0.0 - eslint-plugin-unused-imports: ^2.0.0 + eslint-plugin-unused-imports: ^3.0.0 hbs-cli: ^1.4.1 json: ^11.0.0 matchstick-as: ^0.4.0 @@ -2559,7 +2521,7 @@ __metadata: prompts: ^2.4.2 semver: ^7.5.4 ts-node: ^10.9.1 - typescript: ^4.9.4 + typescript: ^5.4.0 uuid: ^9.0.0 ws: ^8.13.0 languageName: unknown @@ -2569,8 +2531,6 @@ __metadata: version: 0.0.0-use.local resolution: "@teller-protocol/v2-contracts@workspace:packages/contracts" dependencies: - "@eth-optimism/hardhat-ovm": ^0.2.2 - "@ethereumjs/vm": ^5.5.3 "@ledgerhq/hw-app-eth": 6.45.10 "@ledgerhq/hw-transport-node-hid": 6.29.8 "@nomicfoundation/hardhat-ethers": ^3.1.0 @@ -2588,53 +2548,50 @@ __metadata: "@types/ethereumjs-abi": ^0.6.3 "@types/fs-extra": ^9.0.11 "@types/mocha": ^9.0.0 - "@types/node": ^16.11.1 + "@types/node": ^20.0.0 "@types/semver": ^7.3.9 - "@typescript-eslint/eslint-plugin": ^5.5.0 - "@typescript-eslint/parser": ^5.5.0 - "@uniswap/v4-core": 1.0.2 + "@typescript-eslint/eslint-plugin": ^7.0.0 + "@typescript-eslint/parser": ^7.0.0 + "@uniswap/v4-core": ^1.0.2 chai: ^4.3.4 chai-as-promised: ^7.1.1 chalk: ^4.1.1 disklet: ^0.5.0 dotenv: ^10.0.0 - eslint: ^7.32.0 + eslint: ^8.56.0 eslint-config-prettier: ^8.3.0 eslint-config-standard-kit: 0.15.1 eslint-plugin-import: ^2.25.2 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^4.0.0 + eslint-plugin-prettier: ^5.0.0 eslint-plugin-simple-import-sort: ^7.0.0 - eslint-plugin-unused-imports: ^2.0.0 + eslint-plugin-unused-imports: ^3.0.0 eth-sig-util: ^3.0.1 - ethereum-waffle: ^3.4.0 ethereumjs-util: ^7.1.5 ethers: ^6.7.0 fs-extra: ^10.0.0 - ganache-cli: ^6.12.2 - hardhat: ^2.16.1 + hardhat: ^2.22.0 hardhat-contract-sizer: ^2.1.1 hardhat-deploy: ^0.11.34 - hardhat-deploy-ethers: ^0.4.1 hardhat-gas-reporter: ^1.0.4 hardhat-shorthand: ^1.0.0 mocha: ^9.1.3 moment: ^2.29.1 mustache: ^4.2.0 node-watch: ^0.7.1 - prettier: ^2.4.1 - prettier-plugin-solidity: ^1.0.0-beta.19 + prettier: ^3.2.0 + prettier-plugin-solidity: ^1.3.0 qrcode-terminal: ^0.12.0 rlp: ^2.2.7 semver: ^7.3.5 solhint: ^3.3.6 solhint-plugin-prettier: ^0.0.5 - solidity-coverage: ^0.7.17 + solidity-coverage: ^0.8.0 solidity-shell: ^0.0.11 ts-node: ^10.3.0 tsconfig-paths: ^3.11.0 typechain: ^8.1.1 - typescript: ^4.3.4 + typescript: ^5.4.0 languageName: unknown linkType: soft @@ -2650,21 +2607,21 @@ __metadata: "@types/prompts": ^2.4.4 "@types/semver": ^7.5.0 "@types/uuid": ^9.0.2 - "@typescript-eslint/eslint-plugin": ^5.5.0 - "@typescript-eslint/parser": ^5.5.0 + "@typescript-eslint/eslint-plugin": ^7.0.0 + "@typescript-eslint/parser": ^7.0.0 assemblyscript: ^0.27.1 async-mutex: ^0.4.0 axios: ^1.4.0 cleaners: ^0.3.16 cli-progress: ^3.12.0 - eslint: ^7.32.0 + eslint: ^8.56.0 eslint-config-prettier: ^8.3.0 eslint-config-standard-kit: 0.15.1 eslint-plugin-import: ^2.25.2 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^4.0.0 + eslint-plugin-prettier: ^5.0.0 eslint-plugin-simple-import-sort: ^7.0.0 - eslint-plugin-unused-imports: ^2.0.0 + eslint-plugin-unused-imports: ^3.0.0 hbs-cli: ^1.4.1 json: ^11.0.0 matchstick-as: ^0.4.0 @@ -2673,7 +2630,7 @@ __metadata: prompts: ^2.4.2 semver: ^7.5.4 ts-node: ^10.9.1 - typescript: ^4.9.4 + typescript: ^5.4.0 uuid: ^9.0.0 ws: ^8.13.0 languageName: unknown @@ -2691,21 +2648,21 @@ __metadata: "@types/prompts": ^2.4.4 "@types/semver": ^7.5.0 "@types/uuid": ^9.0.2 - "@typescript-eslint/eslint-plugin": ^5.5.0 - "@typescript-eslint/parser": ^5.5.0 + "@typescript-eslint/eslint-plugin": ^7.0.0 + "@typescript-eslint/parser": ^7.0.0 assemblyscript: ^0.27.1 async-mutex: ^0.4.0 axios: ^1.4.0 cleaners: ^0.3.16 cli-progress: ^3.12.0 - eslint: ^7.32.0 + eslint: ^8.56.0 eslint-config-prettier: ^8.3.0 eslint-config-standard-kit: 0.15.1 eslint-plugin-import: ^2.25.2 eslint-plugin-node: ^11.1.0 - eslint-plugin-prettier: ^4.0.0 + eslint-plugin-prettier: ^5.0.0 eslint-plugin-simple-import-sort: ^7.0.0 - eslint-plugin-unused-imports: ^2.0.0 + eslint-plugin-unused-imports: ^3.0.0 hbs-cli: ^1.4.1 json: ^11.0.0 matchstick-as: ^0.4.0 @@ -2714,7 +2671,7 @@ __metadata: prompts: ^2.4.2 semver: ^7.5.4 ts-node: ^10.9.1 - typescript: ^4.9.4 + typescript: ^5.4.0 uuid: ^9.0.0 ws: ^8.13.0 languageName: unknown @@ -2727,36 +2684,6 @@ __metadata: languageName: node linkType: hard -"@truffle/error@npm:^0.1.1": - version: 0.1.1 - resolution: "@truffle/error@npm:0.1.1" - checksum: 32c6faca2d221560456e54709b344533bacdbd575506c9feaeffe27ffb8720839a36fd2c0318da2be5bb824c7aa253d2697e4f5ff5d5b0674e937fdd6f024e07 - languageName: node - linkType: hard - -"@truffle/interface-adapter@npm:^0.5.23": - version: 0.5.23 - resolution: "@truffle/interface-adapter@npm:0.5.23" - dependencies: - bn.js: ^5.1.3 - ethers: ^4.0.32 - web3: 1.7.4 - checksum: ec7cd304313e42937112ef0f1c2f30ee10c84e4c801396cd148b51faa848c79dc250b2392e2e86f097fd1031e4cddfe9bcf99a18a118cc71a0e6bd44eb17551f - languageName: node - linkType: hard - -"@truffle/provider@npm:^0.2.24": - version: 0.2.62 - resolution: "@truffle/provider@npm:0.2.62" - dependencies: - "@truffle/error": ^0.1.1 - "@truffle/interface-adapter": ^0.5.23 - debug: ^4.3.1 - web3: 1.7.4 - checksum: 9c8426fb5e7b8c7106905f9d4502f8364baa4127cf95d0d5c128d42f64d23091a1a03b6560a5a459b0dfa7682bc6147dea69cc250134e876ae0b5522dc4a08a9 - languageName: node - linkType: hard - "@tsconfig/node10@npm:^1.0.7": version: 1.0.9 resolution: "@tsconfig/node10@npm:1.0.9" @@ -2785,18 +2712,6 @@ __metadata: languageName: node linkType: hard -"@typechain/ethers-v5@npm:^2.0.0": - version: 2.0.0 - resolution: "@typechain/ethers-v5@npm:2.0.0" - dependencies: - ethers: ^5.0.2 - peerDependencies: - ethers: ^5.0.0 - typechain: ^3.0.0 - checksum: 785430547f11de358c4018338f6f72aac113ece70d743aad410fff4eacbc3b4876d2e0d3389e1a56123afcf156f5c044ee72275342e45218448c23fe93d23915 - languageName: node - linkType: hard - "@typechain/ethers-v6@npm:^0.4.0": version: 0.4.0 resolution: "@typechain/ethers-v6@npm:0.4.0" @@ -2825,14 +2740,7 @@ __metadata: languageName: node linkType: hard -"@types/abstract-leveldown@npm:*": - version: 7.2.0 - resolution: "@types/abstract-leveldown@npm:7.2.0" - checksum: f719ce076f65e47386ad412dbc6c89a6833a812ee2b2361b89a97480c69180cf9686effdabd0c76819ee5eaefeb18b19ae7dc54c06855261db0070a849124d90 - languageName: node - linkType: hard - -"@types/bn.js@npm:^4.11.3, @types/bn.js@npm:^4.11.5": +"@types/bn.js@npm:^4.11.3": version: 4.11.6 resolution: "@types/bn.js@npm:4.11.6" dependencies: @@ -2949,13 +2857,6 @@ __metadata: languageName: node linkType: hard -"@types/json-schema@npm:^7.0.9": - version: 7.0.9 - resolution: "@types/json-schema@npm:7.0.9" - checksum: 259d0e25f11a21ba5c708f7ea47196bd396e379fddb79c76f9f4f62c945879dc21657904914313ec2754e443c5018ea8372362f323f30e0792897fdb2098a705 - languageName: node - linkType: hard - "@types/json5@npm:^0.0.29": version: 0.0.29 resolution: "@types/json5@npm:0.0.29" @@ -2963,7 +2864,7 @@ __metadata: languageName: node linkType: hard -"@types/keyv@npm:*, @types/keyv@npm:^3.1.1": +"@types/keyv@npm:*": version: 3.1.4 resolution: "@types/keyv@npm:3.1.4" dependencies: @@ -2972,24 +2873,6 @@ __metadata: languageName: node linkType: hard -"@types/level-errors@npm:*": - version: 3.0.0 - resolution: "@types/level-errors@npm:3.0.0" - checksum: ad9392663439306677ac9cb704f8fa0b64c300dfea4f3494369eb78a2e09c194156cbab2b52c71a361a09b735d54a2de65195dcadba0ec7db1d14a320198133e - languageName: node - linkType: hard - -"@types/levelup@npm:^4.3.0": - version: 4.3.3 - resolution: "@types/levelup@npm:4.3.3" - dependencies: - "@types/abstract-leveldown": "*" - "@types/level-errors": "*" - "@types/node": "*" - checksum: 04969bb805035960b8d6650e8f76893be7ba70267bb7012f6f00d67a0cf096ada552355629791b3f5925e9cdb6912d3fe08892c33c3c583e8fd02099b573bdd7 - languageName: node - linkType: hard - "@types/long@npm:^4.0.1": version: 4.0.2 resolution: "@types/long@npm:4.0.2" @@ -2997,13 +2880,6 @@ __metadata: languageName: node linkType: hard -"@types/lru-cache@npm:^5.1.0": - version: 5.1.1 - resolution: "@types/lru-cache@npm:5.1.1" - checksum: e1d6c0085f61b16ec5b3073ec76ad1be4844ea036561c3f145fc19f71f084b58a6eb600b14128aa95809d057d28f1d147c910186ae51219f58366ffd2ff2e118 - languageName: node - linkType: hard - "@types/minimatch@npm:*": version: 5.1.2 resolution: "@types/minimatch@npm:5.1.2" @@ -3018,15 +2894,6 @@ __metadata: languageName: node linkType: hard -"@types/mkdirp@npm:^0.5.2": - version: 0.5.2 - resolution: "@types/mkdirp@npm:0.5.2" - dependencies: - "@types/node": "*" - checksum: 21e6681ee18cee6314dbe0f57ada48981912b76de8266f438ba2573770d60aaa8dd376baad3f20e2346696a7cca84b0aadd1737222341553a0091831a46e6ad1 - languageName: node - linkType: hard - "@types/mocha@npm:^9.0.0": version: 9.1.1 resolution: "@types/mocha@npm:9.1.1" @@ -3034,16 +2901,6 @@ __metadata: languageName: node linkType: hard -"@types/node-fetch@npm:^2.5.5": - version: 2.6.2 - resolution: "@types/node-fetch@npm:2.6.2" - dependencies: - "@types/node": "*" - form-data: ^3.0.0 - checksum: 6f73b1470000d303d25a6fb92875ea837a216656cb7474f66cdd67bb014aa81a5a11e7ac9c21fe19bee9ecb2ef87c1962bceeaec31386119d1ac86e4c30ad7a6 - languageName: node - linkType: hard - "@types/node@npm:*": version: 16.11.4 resolution: "@types/node@npm:16.11.4" @@ -3079,10 +2936,12 @@ __metadata: languageName: node linkType: hard -"@types/node@npm:^16.11.1": - version: 16.18.1 - resolution: "@types/node@npm:16.18.1" - checksum: 0980426defd01b30e46a40725dc40b2d05603a389287804ba325449b0996b3c45e46b9d90468593c399478b131910bcaee39bd6813f7e44452a47de509c17fdd +"@types/node@npm:^20.0.0": + version: 20.19.35 + resolution: "@types/node@npm:20.19.35" + dependencies: + undici-types: ~6.21.0 + checksum: 465aac31b208bd4248f64b05abd0218509c696c55f62ae000571427e357168650d4c484f4531c37ad3be2a75198ba13f9dda7a0c14c539b09cf52b529d7f0d66 languageName: node linkType: hard @@ -3140,25 +2999,6 @@ __metadata: languageName: node linkType: hard -"@types/readable-stream@npm:^2.3.13": - version: 2.3.15 - resolution: "@types/readable-stream@npm:2.3.15" - dependencies: - "@types/node": "*" - safe-buffer: ~5.1.1 - checksum: ec36f525cad09b6c65a1dafcb5ad99b9e2ed824ec49b7aa23180ac427e5d35b8a0706193ecd79ab4253a283ad485ba03d5917a98daaaa144f0ea34f4823e9d82 - languageName: node - linkType: hard - -"@types/resolve@npm:^0.0.8": - version: 0.0.8 - resolution: "@types/resolve@npm:0.0.8" - dependencies: - "@types/node": "*" - checksum: f241bb773ab14b14500623ac3b57c52006ce32b20426b6d8bf2fe5fdc0344f42c77ac0f94ff57b443ae1d320a1a86c62b4e47239f0321699404402fbeb24bad6 - languageName: node - linkType: hard - "@types/responselike@npm:*, @types/responselike@npm:^1.0.0": version: 1.0.0 resolution: "@types/responselike@npm:1.0.0" @@ -3214,103 +3054,121 @@ __metadata: languageName: node linkType: hard -"@typescript-eslint/eslint-plugin@npm:^5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/eslint-plugin@npm:5.5.0" +"@typescript-eslint/eslint-plugin@npm:^7.0.0": + version: 7.18.0 + resolution: "@typescript-eslint/eslint-plugin@npm:7.18.0" dependencies: - "@typescript-eslint/experimental-utils": 5.5.0 - "@typescript-eslint/scope-manager": 5.5.0 - debug: ^4.3.2 - functional-red-black-tree: ^1.0.1 - ignore: ^5.1.8 - regexpp: ^3.2.0 - semver: ^7.3.5 - tsutils: ^3.21.0 + "@eslint-community/regexpp": ^4.10.0 + "@typescript-eslint/scope-manager": 7.18.0 + "@typescript-eslint/type-utils": 7.18.0 + "@typescript-eslint/utils": 7.18.0 + "@typescript-eslint/visitor-keys": 7.18.0 + graphemer: ^1.4.0 + ignore: ^5.3.1 + natural-compare: ^1.4.0 + ts-api-utils: ^1.3.0 peerDependencies: - "@typescript-eslint/parser": ^5.0.0 - eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 + "@typescript-eslint/parser": ^7.0.0 + eslint: ^8.56.0 peerDependenciesMeta: typescript: optional: true - checksum: 49e68e44fe63b9202fb148811450637b8025f14e3e9aef5762dfc4e11b2edcd972948b60e849a0c93f3d381492d39dc45b032bc2b5a74a3abdf07fbb8d2ea0b3 - languageName: node - linkType: hard - -"@typescript-eslint/experimental-utils@npm:5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/experimental-utils@npm:5.5.0" - dependencies: - "@types/json-schema": ^7.0.9 - "@typescript-eslint/scope-manager": 5.5.0 - "@typescript-eslint/types": 5.5.0 - "@typescript-eslint/typescript-estree": 5.5.0 - eslint-scope: ^5.1.1 - eslint-utils: ^3.0.0 - peerDependencies: - eslint: "*" - checksum: 99f4edfb233aa4cb20caf15e92cbecf7415cc1e43cef9b52afe04012844b1fb7fae5e863bdc02235d66a1a9f6d27e1f9c3b99da13156699d6d20aea1b4e0139b + checksum: dfcf150628ca2d4ccdfc20b46b0eae075c2f16ef5e70d9d2f0d746acf4c69a09f962b93befee01a529f14bbeb3e817b5aba287d7dd0edc23396bc5ed1f448c3d languageName: node linkType: hard -"@typescript-eslint/parser@npm:^5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/parser@npm:5.5.0" +"@typescript-eslint/parser@npm:^7.0.0": + version: 7.18.0 + resolution: "@typescript-eslint/parser@npm:7.18.0" dependencies: - "@typescript-eslint/scope-manager": 5.5.0 - "@typescript-eslint/types": 5.5.0 - "@typescript-eslint/typescript-estree": 5.5.0 - debug: ^4.3.2 + "@typescript-eslint/scope-manager": 7.18.0 + "@typescript-eslint/types": 7.18.0 + "@typescript-eslint/typescript-estree": 7.18.0 + "@typescript-eslint/visitor-keys": 7.18.0 + debug: ^4.3.4 peerDependencies: - eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 + eslint: ^8.56.0 peerDependenciesMeta: typescript: optional: true - checksum: 971640eea5bb02c86bc993b2035842c85d6d9f500f1846ce7e3f616e78ad99224a114ada75b0cb2401ba773932895230748953518658724d5500a5f9d79861c6 + checksum: 132b56ac3b2d90b588d61d005a70f6af322860974225b60201cbf45abf7304d67b7d8a6f0ade1c188ac4e339884e78d6dcd450417f1481998f9ddd155bab0801 languageName: node linkType: hard -"@typescript-eslint/scope-manager@npm:5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/scope-manager@npm:5.5.0" +"@typescript-eslint/scope-manager@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/scope-manager@npm:7.18.0" dependencies: - "@typescript-eslint/types": 5.5.0 - "@typescript-eslint/visitor-keys": 5.5.0 - checksum: 6f96c5534d997d6246bd9528a719039e59f01b77476ba2837bbc4b17288305537f49abbf812cfa9911b67b0c265b2616b198537b3d963e7e7747b25940e38f23 + "@typescript-eslint/types": 7.18.0 + "@typescript-eslint/visitor-keys": 7.18.0 + checksum: b982c6ac13d8c86bb3b949c6b4e465f3f60557c2ccf4cc229799827d462df56b9e4d3eaed7711d79b875422fc3d71ec1ebcb5195db72134d07c619e3c5506b57 languageName: node linkType: hard -"@typescript-eslint/types@npm:5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/types@npm:5.5.0" - checksum: 4a8f6902affba3ecc84f486508f42134571bfb28f18f260a4858bf2878105deca711a89c29c60dfd00b9eb0fea8a814ecf51392e9cc91a77fafc824d2bc947d8 +"@typescript-eslint/type-utils@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/type-utils@npm:7.18.0" + dependencies: + "@typescript-eslint/typescript-estree": 7.18.0 + "@typescript-eslint/utils": 7.18.0 + debug: ^4.3.4 + ts-api-utils: ^1.3.0 + peerDependencies: + eslint: ^8.56.0 + peerDependenciesMeta: + typescript: + optional: true + checksum: 68fd5df5146c1a08cde20d59b4b919acab06a1b06194fe4f7ba1b928674880249890785fbbc97394142f2ef5cff5a7fba9b8a940449e7d5605306505348e38bc languageName: node linkType: hard -"@typescript-eslint/typescript-estree@npm:5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/typescript-estree@npm:5.5.0" +"@typescript-eslint/types@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/types@npm:7.18.0" + checksum: 7df2750cd146a0acd2d843208d69f153b458e024bbe12aab9e441ad2c56f47de3ddfeb329c4d1ea0079e2577fea4b8c1c1ce15315a8d49044586b04fedfe7a4d + languageName: node + linkType: hard + +"@typescript-eslint/typescript-estree@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/typescript-estree@npm:7.18.0" dependencies: - "@typescript-eslint/types": 5.5.0 - "@typescript-eslint/visitor-keys": 5.5.0 - debug: ^4.3.2 - globby: ^11.0.4 + "@typescript-eslint/types": 7.18.0 + "@typescript-eslint/visitor-keys": 7.18.0 + debug: ^4.3.4 + globby: ^11.1.0 is-glob: ^4.0.3 - semver: ^7.3.5 - tsutils: ^3.21.0 + minimatch: ^9.0.4 + semver: ^7.6.0 + ts-api-utils: ^1.3.0 peerDependenciesMeta: typescript: optional: true - checksum: 4a8ec6bacf446cdf030ac0b49f67b26c4d259ba70862e7622c7bd29a567a0815970ff902ab35f1f48423e217e97944d7f746779d34dbaf46423894e6a546055d + checksum: c82d22ec9654973944f779eb4eb94c52f4a6eafaccce2f0231ff7757313f3a0d0256c3252f6dfe6d43f57171d09656478acb49a629a9d0c193fb959bc3f36116 languageName: node linkType: hard -"@typescript-eslint/visitor-keys@npm:5.5.0": - version: 5.5.0 - resolution: "@typescript-eslint/visitor-keys@npm:5.5.0" +"@typescript-eslint/utils@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/utils@npm:7.18.0" + dependencies: + "@eslint-community/eslint-utils": ^4.4.0 + "@typescript-eslint/scope-manager": 7.18.0 + "@typescript-eslint/types": 7.18.0 + "@typescript-eslint/typescript-estree": 7.18.0 + peerDependencies: + eslint: ^8.56.0 + checksum: 751dbc816dab8454b7dc6b26a56671dbec08e3f4ef94c2661ce1c0fc48fa2d05a64e03efe24cba2c22d03ba943cd3c5c7a5e1b7b03bbb446728aec1c640bd767 + languageName: node + linkType: hard + +"@typescript-eslint/visitor-keys@npm:7.18.0": + version: 7.18.0 + resolution: "@typescript-eslint/visitor-keys@npm:7.18.0" dependencies: - "@typescript-eslint/types": 5.5.0 - eslint-visitor-keys: ^3.0.0 - checksum: 490be847c58d7159d2d5e0d0686ce4fdd80c61b085caba58d4cba04c4905a56e31c375db674e331fdf7ed96aa16a98f6f7471d656f978799b172bcdb62ca742b + "@typescript-eslint/types": 7.18.0 + eslint-visitor-keys: ^3.4.3 + checksum: 6e806a7cdb424c5498ea187a5a11d0fef7e4602a631be413e7d521e5aec1ab46ba00c76cfb18020adaa0a8c9802354a163bfa0deb74baa7d555526c7517bb158 languageName: node linkType: hard @@ -3321,7 +3179,14 @@ __metadata: languageName: node linkType: hard -"@uniswap/v4-core@npm:1.0.2": +"@ungap/structured-clone@npm:^1.2.0": + version: 1.3.0 + resolution: "@ungap/structured-clone@npm:1.3.0" + checksum: 64ed518f49c2b31f5b50f8570a1e37bde3b62f2460042c50f132430b2d869c4a6586f13aa33a58a4722715b8158c68cae2827389d6752ac54da2893c83e480fc + languageName: node + linkType: hard + +"@uniswap/v4-core@npm:^1.0.2": version: 1.0.2 resolution: "@uniswap/v4-core@npm:1.0.2" checksum: 9dfb3849d7160e94a0ed25025fe51e3b08f9a86361cf322c90003330f8127403021258dc0241a86ceb111e3fd3c2a60290a14ac262310de6360ce30125db4de4 @@ -3361,13 +3226,6 @@ __metadata: languageName: node linkType: hard -"@yarnpkg/lockfile@npm:^1.1.0": - version: 1.1.0 - resolution: "@yarnpkg/lockfile@npm:1.1.0" - checksum: 05b881b4866a3546861fee756e6d3812776ea47fa6eb7098f983d6d0eefa02e12b66c3fff931574120f196286a7ad4879ce02743c8bb2be36c6a576c7852083a - languageName: node - linkType: hard - "JSONStream@npm:1.3.2": version: 1.3.2 resolution: "JSONStream@npm:1.3.2" @@ -3437,83 +3295,6 @@ __metadata: languageName: node linkType: hard -"abstract-level@npm:^1.0.0, abstract-level@npm:^1.0.2, abstract-level@npm:^1.0.3": - version: 1.0.3 - resolution: "abstract-level@npm:1.0.3" - dependencies: - buffer: ^6.0.3 - catering: ^2.1.0 - is-buffer: ^2.0.5 - level-supports: ^4.0.0 - level-transcoder: ^1.0.1 - module-error: ^1.0.1 - queue-microtask: ^1.2.3 - checksum: 70d61a3924526ebc257b138992052f9ff571a6cee5a7660836e37a1cc7081273c3acf465dd2f5e1897b38dc743a6fd9dba14a5d8a2a9d39e5787cd3da99f301d - languageName: node - linkType: hard - -"abstract-leveldown@npm:3.0.0": - version: 3.0.0 - resolution: "abstract-leveldown@npm:3.0.0" - dependencies: - xtend: ~4.0.0 - checksum: 1d3e65fc2288fd17955df3b0887fdd3d4fa7fcd816062014f872ea12a1e86e886151cbdc36abd2f243a810b7999252eaa30adf636ffe1be3103493ab37277e49 - languageName: node - linkType: hard - -"abstract-leveldown@npm:^2.4.1, abstract-leveldown@npm:~2.7.1": - version: 2.7.2 - resolution: "abstract-leveldown@npm:2.7.2" - dependencies: - xtend: ~4.0.0 - checksum: 97c45a05d8b5d24edf3855c1f9a19f919c4a189e387929745289a53116c80638339a7d4e50ad76d0ad2900166adaeaf2e0350dcdcd453e783cd8f04fd9bea17a - languageName: node - linkType: hard - -"abstract-leveldown@npm:^5.0.0, abstract-leveldown@npm:~5.0.0": - version: 5.0.0 - resolution: "abstract-leveldown@npm:5.0.0" - dependencies: - xtend: ~4.0.0 - checksum: d55d03cc7fad011d5fea30d26504b1a76123ec8edd3623d21f80ce0561c610b7ed1e00eb037c14746ec2b7ad8638586024f11d4a1476beee2c470c8cf27e3586 - languageName: node - linkType: hard - -"abstract-leveldown@npm:^6.2.1": - version: 6.3.0 - resolution: "abstract-leveldown@npm:6.3.0" - dependencies: - buffer: ^5.5.0 - immediate: ^3.2.3 - level-concat-iterator: ~2.0.0 - level-supports: ~1.0.0 - xtend: ~4.0.0 - checksum: 121a8509d8c6a540e656c2a69e5b8d853d4df71072011afefc868b98076991bb00120550e90643de9dc18889c675f62413409eeb4c8c204663124c7d215e4ec3 - languageName: node - linkType: hard - -"abstract-leveldown@npm:~2.6.0": - version: 2.6.3 - resolution: "abstract-leveldown@npm:2.6.3" - dependencies: - xtend: ~4.0.0 - checksum: 87b18580467c303c34c305620e2c3227010f64187d6b1cd60c2d1b9adc058b0c4de716e111e9493aaad0080cb7836601032c5084990cd713f86b6a78f1fab791 - languageName: node - linkType: hard - -"abstract-leveldown@npm:~6.2.1": - version: 6.2.3 - resolution: "abstract-leveldown@npm:6.2.3" - dependencies: - buffer: ^5.5.0 - immediate: ^3.2.3 - level-concat-iterator: ~2.0.0 - level-supports: ~1.0.0 - xtend: ~4.0.0 - checksum: 00202b2eb7955dd7bc04f3e44d225e60160cedb8f96fe6ae0e6dca9c356d57071f001ece8ae1d53f48095c4c036d92b3440f2bc7666730610ddea030f9fbde4a - languageName: node - linkType: hard - "accepts@npm:~1.3.8": version: 1.3.8 resolution: "accepts@npm:1.3.8" @@ -3524,7 +3305,7 @@ __metadata: languageName: node linkType: hard -"acorn-jsx@npm:^5.0.0, acorn-jsx@npm:^5.3.1": +"acorn-jsx@npm:^5.0.0, acorn-jsx@npm:^5.3.2": version: 5.3.2 resolution: "acorn-jsx@npm:5.3.2" peerDependencies: @@ -3549,15 +3330,6 @@ __metadata: languageName: node linkType: hard -"acorn@npm:^7.4.0": - version: 7.4.1 - resolution: "acorn@npm:7.4.1" - bin: - acorn: bin/acorn - checksum: 1860f23c2107c910c6177b7b7be71be350db9e1080d814493fae143ae37605189504152d1ba8743ba3178d0b37269ce1ffc42b101547fdc1827078f82671e407 - languageName: node - linkType: hard - "acorn@npm:^8.4.1": version: 8.8.1 resolution: "acorn@npm:8.8.1" @@ -3567,10 +3339,12 @@ __metadata: languageName: node linkType: hard -"address@npm:^1.0.1": - version: 1.2.1 - resolution: "address@npm:1.2.1" - checksum: e4c0f961464ccad09c3f7ed3a8d12f609354a87dd1ad379e43661e9684446fbf158be3edeef85e1590dfc6c88c0897c5908bc18f232eb86e43993a2ada5820fa +"acorn@npm:^8.9.0": + version: 8.16.0 + resolution: "acorn@npm:8.16.0" + bin: + acorn: bin/acorn + checksum: bbfa466cd0dbd18b4460a85e9d0fc2f35db999380892403c573261beda91f23836db2aa71fd3ae65e94424ad14ff8e2b7bd37c7a2624278fd89137cd6e448c41 languageName: node linkType: hard @@ -3595,13 +3369,6 @@ __metadata: languageName: node linkType: hard -"aes-js@npm:^3.1.1": - version: 3.1.2 - resolution: "aes-js@npm:3.1.2" - checksum: 062154d50b1e433cc8c3b8ca7879f3a6375d5e79c2a507b2b6c4ec920b4cd851bf2afa7f65c98761a9da89c0ab618cbe6529e8e9a1c71f93290b53128fb8f712 - languageName: node - linkType: hard - "agent-base@npm:6, agent-base@npm:^6.0.2": version: 6.0.2 resolution: "agent-base@npm:6.0.2" @@ -3632,7 +3399,7 @@ __metadata: languageName: node linkType: hard -"ajv@npm:^6.10.0, ajv@npm:^6.10.2, ajv@npm:^6.12.3, ajv@npm:^6.12.4, ajv@npm:^6.6.1, ajv@npm:^6.9.1": +"ajv@npm:^6.10.2, ajv@npm:^6.12.3, ajv@npm:^6.12.4, ajv@npm:^6.6.1, ajv@npm:^6.9.1": version: 6.12.6 resolution: "ajv@npm:6.12.6" dependencies: @@ -3676,6 +3443,15 @@ __metadata: languageName: node linkType: hard +"ansi-align@npm:^3.0.0": + version: 3.0.1 + resolution: "ansi-align@npm:3.0.1" + dependencies: + string-width: ^4.1.0 + checksum: 6abfa08f2141d231c257162b15292467081fa49a208593e055c866aa0455b57f3a86b5a678c190c618faa79b4c59e254493099cb700dd9cf2293c6be2c8f5d8d + languageName: node + linkType: hard + "ansi-colors@npm:3.2.3": version: 3.2.3 resolution: "ansi-colors@npm:3.2.3" @@ -3690,6 +3466,13 @@ __metadata: languageName: node linkType: hard +"ansi-colors@npm:^4.1.3": + version: 4.1.3 + resolution: "ansi-colors@npm:4.1.3" + checksum: a9c2ec842038a1fabc7db9ece7d3177e2fe1c5dc6f0c51ecfbf5f39911427b89c00b5dc6b8bd95f82a26e9b16aaae2e83d45f060e98070ce4d1333038edceb0e + languageName: node + linkType: hard + "ansi-escapes@npm:^1.0.0, ansi-escapes@npm:^1.1.0": version: 1.4.0 resolution: "ansi-escapes@npm:1.4.0" @@ -3886,45 +3669,6 @@ __metadata: languageName: node linkType: hard -"arr-diff@npm:^4.0.0": - version: 4.0.0 - resolution: "arr-diff@npm:4.0.0" - checksum: ea7c8834842ad3869297f7915689bef3494fd5b102ac678c13ffccab672d3d1f35802b79e90c4cfec2f424af3392e44112d1ccf65da34562ed75e049597276a0 - languageName: node - linkType: hard - -"arr-flatten@npm:^1.1.0": - version: 1.1.0 - resolution: "arr-flatten@npm:1.1.0" - checksum: 963fe12564fca2f72c055f3f6c206b9e031f7c433a0c66ca9858b484821f248c5b1e5d53c8e4989d80d764cd776cf6d9b160ad05f47bdc63022bfd63b5455e22 - languageName: node - linkType: hard - -"arr-union@npm:^3.1.0": - version: 3.1.0 - resolution: "arr-union@npm:3.1.0" - checksum: b5b0408c6eb7591143c394f3be082fee690ddd21f0fdde0a0a01106799e847f67fcae1b7e56b0a0c173290e29c6aca9562e82b300708a268bc8f88f3d6613cb9 - languageName: node - linkType: hard - -"array-back@npm:^1.0.3, array-back@npm:^1.0.4": - version: 1.0.4 - resolution: "array-back@npm:1.0.4" - dependencies: - typical: ^2.6.0 - checksum: 37a8be4cd4920b3d07bdbef40dae83bb37948f5d49601da98a6e48ba5496e9a0008e7f3f2184bcf4d3501bd371a048c9bdca7dc3cc5c3d5b1eb189bbba7b55db - languageName: node - linkType: hard - -"array-back@npm:^2.0.0": - version: 2.0.0 - resolution: "array-back@npm:2.0.0" - dependencies: - typical: ^2.6.1 - checksum: ab36ab3504b25116b47541fb0ac78ff13d1e991f33d98c361edd3aada3ed818a900b619bd67b195dd4e41b9256c27e8cdd6a69ece507e482f1207d07670ed6bd - languageName: node - linkType: hard - "array-back@npm:^3.0.1, array-back@npm:^3.1.0": version: 3.1.0 resolution: "array-back@npm:3.1.0" @@ -3983,13 +3727,6 @@ __metadata: languageName: node linkType: hard -"array-unique@npm:^0.3.2": - version: 0.3.2 - resolution: "array-unique@npm:0.3.2" - checksum: da344b89cfa6b0a5c221f965c21638bfb76b57b45184a01135382186924f55973cd9b171d4dad6bf606c6d9d36b0d721d091afdc9791535ead97ccbe78f8a888 - languageName: node - linkType: hard - "array.prototype.findlast@npm:^1.2.2": version: 1.2.3 resolution: "array.prototype.findlast@npm:1.2.3" @@ -4135,13 +3872,6 @@ __metadata: languageName: node linkType: hard -"assign-symbols@npm:^1.0.0": - version: 1.0.0 - resolution: "assign-symbols@npm:1.0.0" - checksum: c0eb895911d05b6b2d245154f70461c5e42c107457972e5ebba38d48967870dee53bcdf6c7047990586daa80fab8dab3cc6300800fbd47b454247fdedd859a2c - languageName: node - linkType: hard - "ast-parents@npm:0.0.1": version: 0.0.1 resolution: "ast-parents@npm:0.0.1" @@ -4163,15 +3893,6 @@ __metadata: languageName: node linkType: hard -"async-eventemitter@npm:^0.2.2, async-eventemitter@npm:^0.2.4": - version: 0.2.4 - resolution: "async-eventemitter@npm:0.2.4" - dependencies: - async: ^2.4.0 - checksum: b9e77e0f58ebd7188c50c23d613d1263e0ab501f5e677e02b57cc97d7032beaf60aafa189887e7105569c791e212df4af00b608be1e9a4c425911d577124911e - languageName: node - linkType: hard - "async-limiter@npm:~1.0.0": version: 1.0.1 resolution: "async-limiter@npm:1.0.1" @@ -4197,40 +3918,13 @@ __metadata: languageName: node linkType: hard -"async@npm:1.x, async@npm:^1.4.2": +"async@npm:1.x": version: 1.5.2 resolution: "async@npm:1.5.2" checksum: fe5d6214d8f15bd51eee5ae8ec5079b228b86d2d595f47b16369dec2e11b3ff75a567bb5f70d12d79006665fbbb7ee0a7ec0e388524eefd454ecbe651c124ebd languageName: node linkType: hard -"async@npm:2.6.2": - version: 2.6.2 - resolution: "async@npm:2.6.2" - dependencies: - lodash: ^4.17.11 - checksum: e5e90a3bcc4d9bf964bfc6b77d63b8f5bee8c14e9a51c3317dbcace44d5b6b1fe01cd4fd347449704a107da7fcd25e1382ee8545957b2702782ae720605cf7a4 - languageName: node - linkType: hard - -"async@npm:^2.0.1, async@npm:^2.1.2, async@npm:^2.4.0, async@npm:^2.5.0": - version: 2.6.4 - resolution: "async@npm:2.6.4" - dependencies: - lodash: ^4.17.14 - checksum: a52083fb32e1ebe1d63e5c5624038bb30be68ff07a6c8d7dfe35e47c93fc144bd8652cbec869e0ac07d57dde387aa5f1386be3559cdee799cb1f789678d88e19 - languageName: node - linkType: hard - -"async@npm:^2.6.1": - version: 2.6.3 - resolution: "async@npm:2.6.3" - dependencies: - lodash: ^4.17.14 - checksum: 5e5561ff8fca807e88738533d620488ac03a5c43fce6c937451f7e35f943d33ad06c24af3f681a48cca3d2b0002b3118faff0a128dc89438a9bf0226f712c499 - languageName: node - linkType: hard - "async@npm:^3.2.3": version: 3.2.4 resolution: "async@npm:3.2.4" @@ -4252,15 +3946,6 @@ __metadata: languageName: node linkType: hard -"atob@npm:^2.1.2": - version: 2.1.2 - resolution: "atob@npm:2.1.2" - bin: - atob: bin/atob.js - checksum: dfeeeb70090c5ebea7be4b9f787f866686c645d9f39a0d184c817252d0cf08455ed25267d79c03254d3be1f03ac399992a792edcd5ffb9c91e097ab5ef42833a - languageName: node - linkType: hard - "available-typed-arrays@npm:^1.0.5": version: 1.0.5 resolution: "available-typed-arrays@npm:1.0.5" @@ -4322,8163 +4007,5831 @@ __metadata: languageName: node linkType: hard -"babel-code-frame@npm:^6.26.0": +"babel-polyfill@npm:^6.3.14": version: 6.26.0 - resolution: "babel-code-frame@npm:6.26.0" + resolution: "babel-polyfill@npm:6.26.0" dependencies: - chalk: ^1.1.3 - esutils: ^2.0.2 - js-tokens: ^3.0.2 - checksum: 9410c3d5a921eb02fa409675d1a758e493323a49e7b9dddb7a2a24d47e61d39ab1129dd29f9175836eac9ce8b1d4c0a0718fcdc57ce0b865b529fd250dbab313 + babel-runtime: ^6.26.0 + core-js: ^2.5.0 + regenerator-runtime: ^0.10.5 + checksum: 6fb1a3c0bfe1b6fc56ce1afcf531878aa629b309277a05fbf3fe950589b24cb4052a6e487db21d318eb5336b68730a21f5ef62166b6cc8aea3406261054d1118 languageName: node linkType: hard -"babel-core@npm:^6.0.14, babel-core@npm:^6.26.0": - version: 6.26.3 - resolution: "babel-core@npm:6.26.3" +"babel-runtime@npm:^5.8.34": + version: 5.8.38 + resolution: "babel-runtime@npm:5.8.38" dependencies: - babel-code-frame: ^6.26.0 - babel-generator: ^6.26.0 - babel-helpers: ^6.24.1 - babel-messages: ^6.23.0 - babel-register: ^6.26.0 - babel-runtime: ^6.26.0 - babel-template: ^6.26.0 - babel-traverse: ^6.26.0 - babel-types: ^6.26.0 - babylon: ^6.18.0 - convert-source-map: ^1.5.1 - debug: ^2.6.9 - json5: ^0.5.1 - lodash: ^4.17.4 - minimatch: ^3.0.4 - path-is-absolute: ^1.0.1 - private: ^0.1.8 - slash: ^1.0.0 - source-map: ^0.5.7 - checksum: 3d6a37e5c69ea7f7d66c2a261cbd7219197f2f938700e6ebbabb6d84a03f2bf86691ffa066866dcb49ba6c4bd702d347c9e0e147660847d709705cf43c964752 + core-js: ^1.0.0 + checksum: fdb063787bdb2c2983cf7a61d8ed6171f21e59ce15e4a567e8737bb2e5dad7fe19b810cd351ba6dea13b487163c4ba8d2420f13a6e2e737a921b1bc2fbec04a9 languageName: node linkType: hard -"babel-generator@npm:^6.26.0": - version: 6.26.1 - resolution: "babel-generator@npm:6.26.1" +"babel-runtime@npm:^6.26.0": + version: 6.26.0 + resolution: "babel-runtime@npm:6.26.0" dependencies: - babel-messages: ^6.23.0 - babel-runtime: ^6.26.0 - babel-types: ^6.26.0 - detect-indent: ^4.0.0 - jsesc: ^1.3.0 - lodash: ^4.17.4 - source-map: ^0.5.7 - trim-right: ^1.0.1 - checksum: 5397f4d4d1243e7157e3336be96c10fcb1f29f73bf2d9842229c71764d9a6431397d249483a38c4d8b1581459e67be4df6f32d26b1666f02d0f5bfc2c2f25193 + core-js: ^2.4.0 + regenerator-runtime: ^0.11.0 + checksum: 8aeade94665e67a73c1ccc10f6fd42ba0c689b980032b70929de7a6d9a12eb87ef51902733f8fefede35afea7a5c3ef7e916a64d503446c1eedc9e3284bd3d50 languageName: node linkType: hard -"babel-helper-builder-binary-assignment-operator-visitor@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-builder-binary-assignment-operator-visitor@npm:6.24.1" - dependencies: - babel-helper-explode-assignable-expression: ^6.24.1 - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 6ef49597837d042980e78284df014972daac7f1f1f2635d978bb2d13990304322f5135f27b8f2d6eb8c4c2459b496ec76e21544e26afbb5dec88f53089e17476 +"balanced-match@npm:^1.0.0": + version: 1.0.2 + resolution: "balanced-match@npm:1.0.2" + checksum: 9706c088a283058a8a99e0bf91b0a2f75497f185980d9ffa8b304de1d9e58ebda7c72c07ebf01dadedaac5b2907b2c6f566f660d62bd336c3468e960403b9d65 languageName: node linkType: hard -"babel-helper-call-delegate@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-call-delegate@npm:6.24.1" +"base-x@npm:^3.0.2, base-x@npm:^3.0.8": + version: 3.0.9 + resolution: "base-x@npm:3.0.9" dependencies: - babel-helper-hoist-variables: ^6.24.1 - babel-runtime: ^6.22.0 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: b6277d6e48c10cf416632f6dfbac77bdf6ba8ec4ac2f6359a77d6b731dae941c2a3ec7f35e1eba78aad2a7e0838197731d1ef75af529055096c4cb7d96432c88 + safe-buffer: ^5.0.1 + checksum: 957101d6fd09e1903e846fd8f69fd7e5e3e50254383e61ab667c725866bec54e5ece5ba49ce385128ae48f9ec93a26567d1d5ebb91f4d56ef4a9cc0d5a5481e8 languageName: node linkType: hard -"babel-helper-define-map@npm:^6.24.1": - version: 6.26.0 - resolution: "babel-helper-define-map@npm:6.26.0" - dependencies: - babel-helper-function-name: ^6.24.1 - babel-runtime: ^6.26.0 - babel-types: ^6.26.0 - lodash: ^4.17.4 - checksum: 08e201eb009a7dbd020232fb7468ac772ebb8cfd33ec9a41113a54f4c90fd1e3474497783d635b8f87d797706323ca0c1758c516a630b0c95277112fc2fe4f13 +"base64-js@npm:^1.0.2, base64-js@npm:^1.3.1": + version: 1.5.1 + resolution: "base64-js@npm:1.5.1" + checksum: 669632eb3745404c2f822a18fc3a0122d2f9a7a13f7fb8b5823ee19d1d2ff9ee5b52c53367176ea4ad093c332fd5ab4bd0ebae5a8e27917a4105a4cfc86b1005 languageName: node linkType: hard -"babel-helper-explode-assignable-expression@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-explode-assignable-expression@npm:6.24.1" +"bcrypt-pbkdf@npm:^1.0.0": + version: 1.0.2 + resolution: "bcrypt-pbkdf@npm:1.0.2" dependencies: - babel-runtime: ^6.22.0 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: 1bafdb51ce3dd95cf25d712d24a0c3c2ae02ff58118c77462f14ede4d8161aaee42c5c759c3d3a3344a5851b8b0f8d16b395713413b8194e1c3264fc5b12b754 + tweetnacl: ^0.14.3 + checksum: 4edfc9fe7d07019609ccf797a2af28351736e9d012c8402a07120c4453a3b789a15f2ee1530dc49eee8f7eb9379331a8dd4b3766042b9e502f74a68e7f662291 languageName: node linkType: hard -"babel-helper-function-name@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-function-name@npm:6.24.1" - dependencies: - babel-helper-get-function-arity: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: d651db9e0b29e135877e90e7858405750a684220d22a6f7c78bb163305a1b322cc1c8bea1bc617625c34d92d0927fdbaa49ee46822e2f86b524eced4c88c7ff0 +"bech32@npm:1.1.4": + version: 1.1.4 + resolution: "bech32@npm:1.1.4" + checksum: 0e98db619191548390d6f09ff68b0253ba7ae6a55db93dfdbb070ba234c1fd3308c0606fbcc95fad50437227b10011e2698b89f0181f6e7f845c499bd14d0f4b languageName: node linkType: hard -"babel-helper-get-function-arity@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-get-function-arity@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 37e344d6c5c00b67a3b378490a5d7ba924bab1c2ccd6ecf1b7da96ca679be12d75fbec6279366ae9772e482fb06a7b48293954dd79cbeba9b947e2db67252fbd +"bignumber.js@npm:^9.0.0": + version: 9.0.1 + resolution: "bignumber.js@npm:9.0.1" + checksum: 6e72f6069d9db32fc8d27561164de9f811b15f9144be61f323d8b36150a239eea50c92e20ba38af2ba5e717af10b8ef12db8f9948fe2ff02bf17ede5239d15d3 languageName: node linkType: hard -"babel-helper-hoist-variables@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-hoist-variables@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 6af1c165d5f0ad192df07daa194d13de77572bd914d2fc9a270d56b93b2705d98eebabf412b1211505535af131fbe95886fcfad8b3a07b4d501c24b9cb8e57fe +"bignumber.js@npm:^9.1.0": + version: 9.1.1 + resolution: "bignumber.js@npm:9.1.1" + checksum: ad243b7e2f9120b112d670bb3d674128f0bd2ca1745b0a6c9df0433bd2c0252c43e6315d944c2ac07b4c639e7496b425e46842773cf89c6a2dcd4f31e5c4b11e languageName: node linkType: hard -"babel-helper-optimise-call-expression@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-optimise-call-expression@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 16e6aba819b473dbf013391f759497df9f57bc7060bc4e5f7f6b60fb03670eb1dec65dd2227601d58f151e9d647e1f676a12466f5e6674379978820fa02c0fbb +"bignumber.js@npm:^9.1.2": + version: 9.3.1 + resolution: "bignumber.js@npm:9.3.1" + checksum: 6ab100271a23a75bb8b99a4b1a34a1a94967ac0b9a52a198147607bd91064e72c6f356380d7a09cd687bf50d81ad2ed1a0a8edfaa90369c9003ed8bb2440d7f0 languageName: node linkType: hard -"babel-helper-regex@npm:^6.24.1": - version: 6.26.0 - resolution: "babel-helper-regex@npm:6.26.0" - dependencies: - babel-runtime: ^6.26.0 - babel-types: ^6.26.0 - lodash: ^4.17.4 - checksum: ab949a4c90ab255abaafd9ec11a4a6dc77dba360875af2bb0822b699c058858773792c1e969c425c396837f61009f30c9ee5ba4b9a8ca87b0779ae1622f89fb3 +"binary-extensions@npm:^2.0.0": + version: 2.2.0 + resolution: "binary-extensions@npm:2.2.0" + checksum: ccd267956c58d2315f5d3ea6757cf09863c5fc703e50fbeb13a7dc849b812ef76e3cf9ca8f35a0c48498776a7478d7b4a0418e1e2b8cb9cb9731f2922aaad7f8 languageName: node linkType: hard -"babel-helper-remap-async-to-generator@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-remap-async-to-generator@npm:6.24.1" +"binary-install-raw@npm:0.0.13": + version: 0.0.13 + resolution: "binary-install-raw@npm:0.0.13" dependencies: - babel-helper-function-name: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: f330943104b61e7f9248d222bd5fe5d3238904ee20643b76197571e14a724723d64a8096b292a60f64788f0efe30176882c376eeebde00657925678e304324f0 + axios: ^0.21.1 + rimraf: ^3.0.2 + tar: ^6.1.0 + checksum: f18515976237100459b4e2983832c941421ed8767c7fbc0ca716aa96210ccdd6c8ae9fdb9e0c39099248ebd8a3f4653560cb0b655192bb3b4efa1f7be204343a languageName: node linkType: hard -"babel-helper-replace-supers@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helper-replace-supers@npm:6.24.1" - dependencies: - babel-helper-optimise-call-expression: ^6.24.1 - babel-messages: ^6.23.0 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: ca1d216c5c6afc6af2ef55ea16777ba99e108780ea25da61d93edb09fd85f5e96c756306e2a21e737c3b0c7a16c99762b62a0e5f529d3865b14029fef7351cba +"binaryen@npm:101.0.0-nightly.20210723": + version: 101.0.0-nightly.20210723 + resolution: "binaryen@npm:101.0.0-nightly.20210723" + bin: + wasm-opt: bin/wasm-opt + checksum: b1f7cc8e9fb4f1530e9454b5ea6deba17e2d863cea4efc6d0ba1b2af2325e9080c29df0ffeaf9708d455705a629a6a4fbef0ac29ed789a4e316b4c1437879f57 languageName: node linkType: hard -"babel-helpers@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-helpers@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - checksum: 751c6010e18648eebae422adfea5f3b5eff70d592d693bfe0f53346227d74b38e6cd2553c4c18de1e64faac585de490eccbd3ab86ba0885bdac42ed4478bc6b0 +"binaryen@npm:102.0.0-nightly.20211028": + version: 102.0.0-nightly.20211028 + resolution: "binaryen@npm:102.0.0-nightly.20211028" + bin: + wasm-opt: bin/wasm-opt + checksum: d360de0f21e35b73e868837278161ae0d3ccca4a2f87bd02c1cf28750ab355e3469a6a56664ca078f3ed5c2baade6575871b63cc61c9f98f101e55fbbe4ff024 languageName: node linkType: hard -"babel-messages@npm:^6.23.0": - version: 6.23.0 - resolution: "babel-messages@npm:6.23.0" - dependencies: - babel-runtime: ^6.22.0 - checksum: c8075c17587a33869e1a5bd0a5b73bbe395b68188362dacd5418debbc7c8fd784bcd3295e81ee7e410dc2c2655755add6af03698c522209f6a68334c15e6d6ca +"binaryen@npm:111.0.0-nightly.20230202": + version: 111.0.0-nightly.20230202 + resolution: "binaryen@npm:111.0.0-nightly.20230202" + bin: + wasm-opt: bin/wasm-opt + wasm2js: bin/wasm2js + checksum: e57afd2c18e3498a25546dd093a100e5d12ac1bc57c6ef40cb2b8777baf2b31b9f6c2dd4be93296127b42bd8b064a86bba01db5b3ca737087b14668ff66a3c88 languageName: node linkType: hard -"babel-plugin-check-es2015-constants@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-check-es2015-constants@npm:6.22.0" +"bindings@npm:^1.5.0": + version: 1.5.0 + resolution: "bindings@npm:1.5.0" dependencies: - babel-runtime: ^6.22.0 - checksum: 39168cb4ff078911726bfaf9d111d1e18f3e99d8b6f6101d343249b28346c3869e415c97fe7e857e7f34b913f8a052634b2b9dcfb4c0272e5f64ed22df69c735 + file-uri-to-path: 1.0.0 + checksum: 65b6b48095717c2e6105a021a7da4ea435aa8d3d3cd085cb9e85bcb6e5773cf318c4745c3f7c504412855940b585bdf9b918236612a1c7a7942491de176f1ae7 languageName: node linkType: hard -"babel-plugin-syntax-async-functions@npm:^6.8.0": - version: 6.13.0 - resolution: "babel-plugin-syntax-async-functions@npm:6.13.0" - checksum: e982d9756869fa83eb6a4502490a90b0d31e8a41e2ee582045934f022ac8ff5fa6a3386366976fab3a391d5a7ab8ea5f9da623f35ed8ab328b8ab6d9b2feb1d3 +"bl@npm:^1.0.0": + version: 1.2.3 + resolution: "bl@npm:1.2.3" + dependencies: + readable-stream: ^2.3.5 + safe-buffer: ^5.1.1 + checksum: 123f097989ce2fa9087ce761cd41176aaaec864e28f7dfe5c7dab8ae16d66d9844f849c3ad688eb357e3c5e4f49b573e3c0780bb8bc937206735a3b6f8569a5f languageName: node linkType: hard -"babel-plugin-syntax-exponentiation-operator@npm:^6.8.0": - version: 6.13.0 - resolution: "babel-plugin-syntax-exponentiation-operator@npm:6.13.0" - checksum: cbcb3aeae7005240325f72d55c3c90575033123e8a1ddfa6bf9eac4ee7e246c2a23f5b5ab1144879590d947a3ed1d88838169d125e5d7c4f53678526482b020e +"bl@npm:^4.0.3": + version: 4.1.0 + resolution: "bl@npm:4.1.0" + dependencies: + buffer: ^5.5.0 + inherits: ^2.0.4 + readable-stream: ^3.4.0 + checksum: 9e8521fa7e83aa9427c6f8ccdcba6e8167ef30cc9a22df26effcc5ab682ef91d2cbc23a239f945d099289e4bbcfae7a192e9c28c84c6202e710a0dfec3722662 languageName: node linkType: hard -"babel-plugin-syntax-trailing-function-commas@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-syntax-trailing-function-commas@npm:6.22.0" - checksum: d8b9039ded835bb128e8e14eeeb6e0ac2a876b85250924bdc3a8dc2a6984d3bfade4de04d40fb15ea04a86d561ac280ae0d7306d7d4ef7a8c52c43b6a23909c6 +"blakejs@npm:^1.1.0": + version: 1.1.1 + resolution: "blakejs@npm:1.1.1" + checksum: 77a0875af41fe0a6b15feacc69a4a730063df697b2932adbde15aa2c9c58a592870cd511a494ceee59cc8143ae64964dfa1bf301dab275b330debcd12c2b3db9 languageName: node linkType: hard -"babel-plugin-transform-async-to-generator@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-async-to-generator@npm:6.24.1" +"blob-to-it@npm:^1.0.1": + version: 1.0.4 + resolution: "blob-to-it@npm:1.0.4" dependencies: - babel-helper-remap-async-to-generator: ^6.24.1 - babel-plugin-syntax-async-functions: ^6.8.0 - babel-runtime: ^6.22.0 - checksum: ffe8b4b2ed6db1f413ede385bd1a36f39e02a64ed79ce02779440049af75215c98f8debdc70eb01430bfd889f792682b0136576fe966f7f9e1b30e2a54695a8d + browser-readablestream-to-it: ^1.0.3 + checksum: e7fbebe5bd7b8187a4a88203639777456596a0cc68372e7b2dbcfbae6dea2b80e2a89522140039b538140bc3e3a6b1e90d1778e725eb8899070f799e61591751 languageName: node linkType: hard -"babel-plugin-transform-es2015-arrow-functions@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-transform-es2015-arrow-functions@npm:6.22.0" - dependencies: - babel-runtime: ^6.22.0 - checksum: 746e2be0fed20771c07f0984ba79ef0bab37d6e98434267ec96cef57272014fe53a180bfb9047bf69ed149d367a2c97baad54d6057531cd037684f371aab2333 +"bluebird@npm:^3.5.0": + version: 3.7.2 + resolution: "bluebird@npm:3.7.2" + checksum: 869417503c722e7dc54ca46715f70e15f4d9c602a423a02c825570862d12935be59ed9c7ba34a9b31f186c017c23cac6b54e35446f8353059c101da73eac22ef languageName: node linkType: hard -"babel-plugin-transform-es2015-block-scoped-functions@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-transform-es2015-block-scoped-functions@npm:6.22.0" - dependencies: - babel-runtime: ^6.22.0 - checksum: f251611f723d94b4068d2a873a2783e019bd81bd7144cfdbcfc31ef166f4d82fa2f1efba64342ba2630dab93a2b12284067725c0aa08315712419a2bc3b92a75 +"bn.js@npm:4.11.6": + version: 4.11.6 + resolution: "bn.js@npm:4.11.6" + checksum: db23047bf06fdf9cf74401c8e76bca9f55313c81df382247d2c753868b368562e69171716b81b7038ada8860af18346fd4bcd1cf9d4963f923fe8e54e61cb58a languageName: node linkType: hard -"babel-plugin-transform-es2015-block-scoping@npm:^6.23.0": - version: 6.26.0 - resolution: "babel-plugin-transform-es2015-block-scoping@npm:6.26.0" - dependencies: - babel-runtime: ^6.26.0 - babel-template: ^6.26.0 - babel-traverse: ^6.26.0 - babel-types: ^6.26.0 - lodash: ^4.17.4 - checksum: 5e4dee33bf4aab0ce7751a9ae845c25d3bf03944ffdfc8d784e1de2123a3eec19657dd59274c9969461757f5e2ab75c517e978bafe5309a821a41e278ad38a63 +"bn.js@npm:^4.0.0, bn.js@npm:^4.1.0, bn.js@npm:^4.11.0, bn.js@npm:^4.11.6, bn.js@npm:^4.11.8, bn.js@npm:^4.11.9": + version: 4.12.0 + resolution: "bn.js@npm:4.12.0" + checksum: 39afb4f15f4ea537b55eaf1446c896af28ac948fdcf47171961475724d1bb65118cca49fa6e3d67706e4790955ec0e74de584e45c8f1ef89f46c812bee5b5a12 languageName: node linkType: hard -"babel-plugin-transform-es2015-classes@npm:^6.23.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-classes@npm:6.24.1" - dependencies: - babel-helper-define-map: ^6.24.1 - babel-helper-function-name: ^6.24.1 - babel-helper-optimise-call-expression: ^6.24.1 - babel-helper-replace-supers: ^6.24.1 - babel-messages: ^6.23.0 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: 999392b47a83cf9297e49fbde00bc9b15fb6d71bc041f7b3d621ac45361486ec4b66f55c47f98dca6c398ceaa8bfc9f3c21257854822c4523e7475a92e6c000a +"bn.js@npm:^5.0.0, bn.js@npm:^5.1.1, bn.js@npm:^5.2.1": + version: 5.2.1 + resolution: "bn.js@npm:5.2.1" + checksum: 3dd8c8d38055fedfa95c1d5fc3c99f8dd547b36287b37768db0abab3c239711f88ff58d18d155dd8ad902b0b0cee973747b7ae20ea12a09473272b0201c9edd3 languageName: node linkType: hard -"babel-plugin-transform-es2015-computed-properties@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-computed-properties@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - checksum: 34e466bfd4b021aa3861db66cf10a9093fa6a4fcedbc8c82a55f6ca1fcbd212a9967f2df6c5f9e9a20046fa43c8967633a476f2bbc15cb8d3769cbba948a5c16 +"bn.js@npm:^5.1.2, bn.js@npm:^5.2.0": + version: 5.2.0 + resolution: "bn.js@npm:5.2.0" + checksum: 6117170393200f68b35a061ecbf55d01dd989302e7b3c798a3012354fa638d124f0b2f79e63f77be5556be80322a09c40339eda6413ba7468524c0b6d4b4cb7a languageName: node linkType: hard -"babel-plugin-transform-es2015-destructuring@npm:^6.23.0": - version: 6.23.0 - resolution: "babel-plugin-transform-es2015-destructuring@npm:6.23.0" +"body-parser@npm:1.20.1, body-parser@npm:^1.16.0": + version: 1.20.1 + resolution: "body-parser@npm:1.20.1" dependencies: - babel-runtime: ^6.22.0 - checksum: 1343d27f09846e6e1e48da7b83d0d4f2d5571559c468ad8ad4c3715b8ff3e21b2d553e90ad420dc6840de260b7f3b9f9c057606d527e3d838a52a3a7c5fffdbe + bytes: 3.1.2 + content-type: ~1.0.4 + debug: 2.6.9 + depd: 2.0.0 + destroy: 1.2.0 + http-errors: 2.0.0 + iconv-lite: 0.4.24 + on-finished: 2.4.1 + qs: 6.11.0 + raw-body: 2.5.1 + type-is: ~1.6.18 + unpipe: 1.0.0 + checksum: f1050dbac3bede6a78f0b87947a8d548ce43f91ccc718a50dd774f3c81f2d8b04693e52acf62659fad23101827dd318da1fb1363444ff9a8482b886a3e4a5266 languageName: node linkType: hard -"babel-plugin-transform-es2015-duplicate-keys@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-duplicate-keys@npm:6.24.1" +"boxen@npm:^5.1.2": + version: 5.1.2 + resolution: "boxen@npm:5.1.2" dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 756a7a13517c3e80c8312137b9872b9bc32fbfbb905e9f1e45bf321e2b464d0e6a6e6deca22c61b62377225bd8136b73580897cccb394995d6e00bc8ce882ba4 + ansi-align: ^3.0.0 + camelcase: ^6.2.0 + chalk: ^4.1.0 + cli-boxes: ^2.2.1 + string-width: ^4.2.2 + type-fest: ^0.20.2 + widest-line: ^3.1.0 + wrap-ansi: ^7.0.0 + checksum: 82d03e42a72576ff235123f17b7c505372fe05c83f75f61e7d4fa4bcb393897ec95ce766fecb8f26b915f0f7a7227d66e5ec7cef43f5b2bd9d3aeed47ec55877 languageName: node linkType: hard -"babel-plugin-transform-es2015-for-of@npm:^6.23.0": - version: 6.23.0 - resolution: "babel-plugin-transform-es2015-for-of@npm:6.23.0" +"brace-expansion@npm:^1.1.7": + version: 1.1.11 + resolution: "brace-expansion@npm:1.1.11" dependencies: - babel-runtime: ^6.22.0 - checksum: 0124e320c32b25de84ddaba951a6f0ad031fa5019de54de32bd317d2a97b3f967026008f32e8c88728330c1cce7c4f1d0ecb15007020d50bd5ca1438a882e205 + balanced-match: ^1.0.0 + concat-map: 0.0.1 + checksum: faf34a7bb0c3fcf4b59c7808bc5d2a96a40988addf2e7e09dfbb67a2251800e0d14cd2bfc1aa79174f2f5095c54ff27f46fb1289fe2d77dac755b5eb3434cc07 languageName: node linkType: hard -"babel-plugin-transform-es2015-function-name@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-function-name@npm:6.24.1" +"brace-expansion@npm:^2.0.1": + version: 2.0.1 + resolution: "brace-expansion@npm:2.0.1" dependencies: - babel-helper-function-name: ^6.24.1 - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 629ecd824d53ec973a3ef85e74d9fd8c710203084ca2f7ac833879ddfa3b83a28f0270fe2ee5f3b8c078bb4b3e4b843173a646a7cd4abc49e8c1c563d31fb711 + balanced-match: ^1.0.0 + checksum: a61e7cd2e8a8505e9f0036b3b6108ba5e926b4b55089eeb5550cd04a471fe216c96d4fe7e4c7f995c728c554ae20ddfc4244cad10aef255e72b62930afd233d1 languageName: node linkType: hard -"babel-plugin-transform-es2015-literals@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-transform-es2015-literals@npm:6.22.0" +"brace-expansion@npm:^2.0.2": + version: 2.0.2 + resolution: "brace-expansion@npm:2.0.2" dependencies: - babel-runtime: ^6.22.0 - checksum: 40e270580a0236990f2555f5dc7ae24b4db9f4709ca455ed1a6724b0078592482274be7448579b14122bd06481641a38e7b2e48d0b49b8c81c88e154a26865b4 + balanced-match: ^1.0.0 + checksum: 01dff195e3646bc4b0d27b63d9bab84d2ebc06121ff5013ad6e5356daa5a9d6b60fa26cf73c74797f2dc3fbec112af13578d51f75228c1112b26c790a87b0488 languageName: node linkType: hard -"babel-plugin-transform-es2015-modules-amd@npm:^6.22.0, babel-plugin-transform-es2015-modules-amd@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-modules-amd@npm:6.24.1" +"braces@npm:^3.0.1, braces@npm:~3.0.2": + version: 3.0.2 + resolution: "braces@npm:3.0.2" dependencies: - babel-plugin-transform-es2015-modules-commonjs: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - checksum: 084c7a1ef3bd0b2b9f4851b27cfb65f8ea1408349af05b4d88f994c23844a0754abfa4799bbc5f3f0ec94232b3a54a2e46d7f1dff1bdd40fa66a46f645197dfa + fill-range: ^7.0.1 + checksum: e2a8e769a863f3d4ee887b5fe21f63193a891c68b612ddb4b68d82d1b5f3ff9073af066c343e9867a393fe4c2555dcb33e89b937195feb9c1613d259edfcd459 languageName: node linkType: hard -"babel-plugin-transform-es2015-modules-commonjs@npm:^6.23.0, babel-plugin-transform-es2015-modules-commonjs@npm:^6.24.1": - version: 6.26.2 - resolution: "babel-plugin-transform-es2015-modules-commonjs@npm:6.26.2" - dependencies: - babel-plugin-transform-strict-mode: ^6.24.1 - babel-runtime: ^6.26.0 - babel-template: ^6.26.0 - babel-types: ^6.26.0 - checksum: 9cd93a84037855c1879bcc100229bee25b44c4805a9a9f040e8927f772c4732fa17a0706c81ea0db77b357dd9baf84388eec03ceb36597932c48fe32fb3d4171 +"brorand@npm:^1.0.1, brorand@npm:^1.1.0": + version: 1.1.0 + resolution: "brorand@npm:1.1.0" + checksum: 8a05c9f3c4b46572dec6ef71012b1946db6cae8c7bb60ccd4b7dd5a84655db49fe043ecc6272e7ef1f69dc53d6730b9e2a3a03a8310509a3d797a618cbee52be languageName: node linkType: hard -"babel-plugin-transform-es2015-modules-systemjs@npm:^6.23.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-modules-systemjs@npm:6.24.1" - dependencies: - babel-helper-hoist-variables: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - checksum: b34877e201d7b4d293d87c04962a3575fe7727a9593e99ce3a7f8deea3da8883a08bd87a6a12927083ac26f47f6944a31cdbfe3d6eb4d18dd884cb2d304ee943 +"browser-readablestream-to-it@npm:^1.0.0, browser-readablestream-to-it@npm:^1.0.1, browser-readablestream-to-it@npm:^1.0.3": + version: 1.0.3 + resolution: "browser-readablestream-to-it@npm:1.0.3" + checksum: 07895bbc54cdeea62c8e9b7e32d374ec5c340ed1d0bc0c6cd6f1e0561ad931b160a3988426c763672ddf38ac1f75e45b9d8ae267b43f387183edafcad625f30a languageName: node linkType: hard -"babel-plugin-transform-es2015-modules-umd@npm:^6.23.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-modules-umd@npm:6.24.1" - dependencies: - babel-plugin-transform-es2015-modules-amd: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - checksum: 735857b9f2ad0c41ceda31a1594fe2a063025f4428f9e243885a437b5bd415aca445a5e8495ff34b7120617735b1c3a2158033f0be23f1f5a90e655fff742a01 +"browser-stdout@npm:1.3.1, browser-stdout@npm:^1.3.1": + version: 1.3.1 + resolution: "browser-stdout@npm:1.3.1" + checksum: b717b19b25952dd6af483e368f9bcd6b14b87740c3d226c2977a65e84666ffd67000bddea7d911f111a9b6ddc822b234de42d52ab6507bce4119a4cc003ef7b3 languageName: node linkType: hard -"babel-plugin-transform-es2015-object-super@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-object-super@npm:6.24.1" +"browserify-aes@npm:^1.0.0, browserify-aes@npm:^1.0.4, browserify-aes@npm:^1.2.0": + version: 1.2.0 + resolution: "browserify-aes@npm:1.2.0" dependencies: - babel-helper-replace-supers: ^6.24.1 - babel-runtime: ^6.22.0 - checksum: 97b2968f699ac94cb55f4f1e7ea53dc9e4264ec99cab826f40f181da9f6db5980cd8b4985f05c7b6f1e19fbc31681e6e63894dfc5ecf4b3a673d736c4ef0f9db + buffer-xor: ^1.0.3 + cipher-base: ^1.0.0 + create-hash: ^1.1.0 + evp_bytestokey: ^1.0.3 + inherits: ^2.0.1 + safe-buffer: ^5.0.1 + checksum: 4a17c3eb55a2aa61c934c286f34921933086bf6d67f02d4adb09fcc6f2fc93977b47d9d884c25619144fccd47b3b3a399e1ad8b3ff5a346be47270114bcf7104 languageName: node linkType: hard -"babel-plugin-transform-es2015-parameters@npm:^6.23.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-parameters@npm:6.24.1" +"browserify-cipher@npm:^1.0.0": + version: 1.0.1 + resolution: "browserify-cipher@npm:1.0.1" dependencies: - babel-helper-call-delegate: ^6.24.1 - babel-helper-get-function-arity: ^6.24.1 - babel-runtime: ^6.22.0 - babel-template: ^6.24.1 - babel-traverse: ^6.24.1 - babel-types: ^6.24.1 - checksum: bb6c047dc10499be8ccebdffac22c77f14aee5d3106da8f2e96c801d2746403c809d8c6922e8ebd2eb31d8827b4bb2321ba43378fcdc9dca206417bb345c4f93 + browserify-aes: ^1.0.4 + browserify-des: ^1.0.0 + evp_bytestokey: ^1.0.0 + checksum: 2d8500acf1ee535e6bebe808f7a20e4c3a9e2ed1a6885fff1facbfd201ac013ef030422bec65ca9ece8ffe82b03ca580421463f9c45af6c8415fd629f4118c13 languageName: node linkType: hard -"babel-plugin-transform-es2015-shorthand-properties@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-shorthand-properties@npm:6.24.1" +"browserify-des@npm:^1.0.0": + version: 1.0.2 + resolution: "browserify-des@npm:1.0.2" dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 9302c5de158a28432e932501a783560094c624c3659f4e0a472b6b2e9d6e8ab2634f82ef74d3e75363d46ccff6aad119267dbc34f67464c70625e24a651ad9e5 + cipher-base: ^1.0.1 + des.js: ^1.0.0 + inherits: ^2.0.1 + safe-buffer: ^5.1.2 + checksum: b15a3e358a1d78a3b62ddc06c845d02afde6fc826dab23f1b9c016e643e7b1fda41de628d2110b712f6a44fb10cbc1800bc6872a03ddd363fb50768e010395b7 languageName: node linkType: hard -"babel-plugin-transform-es2015-spread@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-transform-es2015-spread@npm:6.22.0" +"browserify-rsa@npm:^4.0.0, browserify-rsa@npm:^4.0.1": + version: 4.1.0 + resolution: "browserify-rsa@npm:4.1.0" dependencies: - babel-runtime: ^6.22.0 - checksum: 8694a8a7802d905503194ab81c155354b36d39fc819ad2148f83146518dd37d2c6926c8568712f5aa890169afc9353fd4bcc49397959c6dc9da3480b449c0ae9 + bn.js: ^5.0.0 + randombytes: ^2.0.1 + checksum: 155f0c135873efc85620571a33d884aa8810e40176125ad424ec9d85016ff105a07f6231650914a760cca66f29af0494087947b7be34880dd4599a0cd3c38e54 languageName: node linkType: hard -"babel-plugin-transform-es2015-sticky-regex@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-sticky-regex@npm:6.24.1" +"browserify-sign@npm:^4.0.0": + version: 4.2.1 + resolution: "browserify-sign@npm:4.2.1" dependencies: - babel-helper-regex: ^6.24.1 - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: d9c45401caf0d74779a1170e886976d4c865b7de2e90dfffc7557481b9e73b6e37e9f1028aa07b813896c4df88f4d7e89968249a74547c7875e6c499c90c801d + bn.js: ^5.1.1 + browserify-rsa: ^4.0.1 + create-hash: ^1.2.0 + create-hmac: ^1.1.7 + elliptic: ^6.5.3 + inherits: ^2.0.4 + parse-asn1: ^5.1.5 + readable-stream: ^3.6.0 + safe-buffer: ^5.2.0 + checksum: 0221f190e3f5b2d40183fa51621be7e838d9caa329fe1ba773406b7637855f37b30f5d83e52ff8f244ed12ffe6278dd9983638609ed88c841ce547e603855707 languageName: node linkType: hard -"babel-plugin-transform-es2015-template-literals@npm:^6.22.0": - version: 6.22.0 - resolution: "babel-plugin-transform-es2015-template-literals@npm:6.22.0" +"bs58@npm:^4.0.0": + version: 4.0.1 + resolution: "bs58@npm:4.0.1" dependencies: - babel-runtime: ^6.22.0 - checksum: 4fad2b7b383a2e784858ee7bf837419ee8ff9602afe218e1472f8c33a0c008f01d06f23ff2f2322fb23e1ed17e37237a818575fe88ecc5417d85331973b0ea4d + base-x: ^3.0.2 + checksum: b3c5365bb9e0c561e1a82f1a2d809a1a692059fae016be233a6127ad2f50a6b986467c3a50669ce4c18929dcccb297c5909314dd347a25a68c21b68eb3e95ac2 languageName: node linkType: hard -"babel-plugin-transform-es2015-typeof-symbol@npm:^6.23.0": - version: 6.23.0 - resolution: "babel-plugin-transform-es2015-typeof-symbol@npm:6.23.0" +"bs58check@npm:^2.1.2": + version: 2.1.2 + resolution: "bs58check@npm:2.1.2" dependencies: - babel-runtime: ^6.22.0 - checksum: 68a1609c6abcddf5f138c56bafcd9fad7c6b3b404fe40910148ab70eb21d6c7807a343a64eb81ce45daf4b70c384c528c55fad45e0d581e4b09efa4d574a6a1b - languageName: node - linkType: hard - -"babel-plugin-transform-es2015-unicode-regex@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-es2015-unicode-regex@npm:6.24.1" - dependencies: - babel-helper-regex: ^6.24.1 - babel-runtime: ^6.22.0 - regexpu-core: ^2.0.0 - checksum: 739ddb02e5f77904f83ea45323c9a636e3aed34b2a49c7c68208b5f2834eecb6b655e772f870f16a7aaf09ac8219f754ad69d61741d088f5b681d13cda69265d + bs58: ^4.0.0 + create-hash: ^1.1.0 + safe-buffer: ^5.1.2 + checksum: 43bdf08a5dd04581b78f040bc4169480e17008da482ffe2a6507327bbc4fc5c28de0501f7faf22901cfe57fbca79cbb202ca529003fedb4cb8dccd265b38e54d languageName: node linkType: hard -"babel-plugin-transform-exponentiation-operator@npm:^6.22.0": - version: 6.24.1 - resolution: "babel-plugin-transform-exponentiation-operator@npm:6.24.1" - dependencies: - babel-helper-builder-binary-assignment-operator-visitor: ^6.24.1 - babel-plugin-syntax-exponentiation-operator: ^6.8.0 - babel-runtime: ^6.22.0 - checksum: 533ad53ba2cd6ff3c0f751563e1beea429c620038dc2efeeb8348ab4752ebcc95d1521857abfd08047400f1921b2d4df5e0cd266e65ddbe4c3edc58b9ad6fd3c +"buffer-alloc-unsafe@npm:^1.1.0": + version: 1.1.0 + resolution: "buffer-alloc-unsafe@npm:1.1.0" + checksum: c5e18bf51f67754ec843c9af3d4c005051aac5008a3992938dda1344e5cfec77c4b02b4ca303644d1e9a6e281765155ce6356d85c6f5ccc5cd21afc868def396 languageName: node linkType: hard -"babel-plugin-transform-regenerator@npm:^6.22.0": - version: 6.26.0 - resolution: "babel-plugin-transform-regenerator@npm:6.26.0" +"buffer-alloc@npm:^1.2.0": + version: 1.2.0 + resolution: "buffer-alloc@npm:1.2.0" dependencies: - regenerator-transform: ^0.10.0 - checksum: 41a51d8f692bf4a5cbd705fa70f3cb6abebae66d9ba3dccfb5921da262f8c30f630e1fe9f7b132e29b96fe0d99385a801f6aa204278c5bd0af4284f7f93a665a + buffer-alloc-unsafe: ^1.1.0 + buffer-fill: ^1.0.0 + checksum: 560cd27f3cbe73c614867da373407d4506309c62fe18de45a1ce191f3785ec6ca2488d802ff82065798542422980ca25f903db078c57822218182c37c3576df5 languageName: node linkType: hard -"babel-plugin-transform-strict-mode@npm:^6.24.1": - version: 6.24.1 - resolution: "babel-plugin-transform-strict-mode@npm:6.24.1" - dependencies: - babel-runtime: ^6.22.0 - babel-types: ^6.24.1 - checksum: 32d70ce9d8c8918a6a840e46df03dfe1e265eb9b25df5a800fedb5065ef1b4b5f24d7c62d92fca0e374db8b0b9b6f84e68edd02ad21883d48f608583ec29f638 +"buffer-fill@npm:^1.0.0": + version: 1.0.0 + resolution: "buffer-fill@npm:1.0.0" + checksum: c29b4723ddeab01e74b5d3b982a0c6828f2ded49cef049ddca3dac661c874ecdbcecb5dd8380cf0f4adbeb8cff90a7de724126750a1f1e5ebd4eb6c59a1315b1 languageName: node linkType: hard -"babel-polyfill@npm:^6.3.14": - version: 6.26.0 - resolution: "babel-polyfill@npm:6.26.0" - dependencies: - babel-runtime: ^6.26.0 - core-js: ^2.5.0 - regenerator-runtime: ^0.10.5 - checksum: 6fb1a3c0bfe1b6fc56ce1afcf531878aa629b309277a05fbf3fe950589b24cb4052a6e487db21d318eb5336b68730a21f5ef62166b6cc8aea3406261054d1118 +"buffer-from@npm:^1.0.0": + version: 1.1.2 + resolution: "buffer-from@npm:1.1.2" + checksum: 0448524a562b37d4d7ed9efd91685a5b77a50672c556ea254ac9a6d30e3403a517d8981f10e565db24e8339413b43c97ca2951f10e399c6125a0d8911f5679bb languageName: node linkType: hard -"babel-preset-env@npm:^1.7.0": - version: 1.7.0 - resolution: "babel-preset-env@npm:1.7.0" - dependencies: - babel-plugin-check-es2015-constants: ^6.22.0 - babel-plugin-syntax-trailing-function-commas: ^6.22.0 - babel-plugin-transform-async-to-generator: ^6.22.0 - babel-plugin-transform-es2015-arrow-functions: ^6.22.0 - babel-plugin-transform-es2015-block-scoped-functions: ^6.22.0 - babel-plugin-transform-es2015-block-scoping: ^6.23.0 - babel-plugin-transform-es2015-classes: ^6.23.0 - babel-plugin-transform-es2015-computed-properties: ^6.22.0 - babel-plugin-transform-es2015-destructuring: ^6.23.0 - babel-plugin-transform-es2015-duplicate-keys: ^6.22.0 - babel-plugin-transform-es2015-for-of: ^6.23.0 - babel-plugin-transform-es2015-function-name: ^6.22.0 - babel-plugin-transform-es2015-literals: ^6.22.0 - babel-plugin-transform-es2015-modules-amd: ^6.22.0 - babel-plugin-transform-es2015-modules-commonjs: ^6.23.0 - babel-plugin-transform-es2015-modules-systemjs: ^6.23.0 - babel-plugin-transform-es2015-modules-umd: ^6.23.0 - babel-plugin-transform-es2015-object-super: ^6.22.0 - babel-plugin-transform-es2015-parameters: ^6.23.0 - babel-plugin-transform-es2015-shorthand-properties: ^6.22.0 - babel-plugin-transform-es2015-spread: ^6.22.0 - babel-plugin-transform-es2015-sticky-regex: ^6.22.0 - babel-plugin-transform-es2015-template-literals: ^6.22.0 - babel-plugin-transform-es2015-typeof-symbol: ^6.23.0 - babel-plugin-transform-es2015-unicode-regex: ^6.22.0 - babel-plugin-transform-exponentiation-operator: ^6.22.0 - babel-plugin-transform-regenerator: ^6.22.0 - browserslist: ^3.2.6 - invariant: ^2.2.2 - semver: ^5.3.0 - checksum: 6e459a6c76086a2a377707680148b94c3d0aba425b039b427ca01171ebada7f5db5d336b309548462f6ba015e13176a4724f912875c15084d4aa88d77020d185 +"buffer-to-arraybuffer@npm:^0.0.5": + version: 0.0.5 + resolution: "buffer-to-arraybuffer@npm:0.0.5" + checksum: b2e6493a6679e03d0e0e146b4258b9a6d92649d528d8fc4a74423b77f0d4f9398c9f965f3378d1683a91738054bae2761196cfe233f41ab3695126cb58cb25f9 languageName: node linkType: hard -"babel-register@npm:^6.26.0": - version: 6.26.0 - resolution: "babel-register@npm:6.26.0" - dependencies: - babel-core: ^6.26.0 - babel-runtime: ^6.26.0 - core-js: ^2.5.0 - home-or-tmp: ^2.0.0 - lodash: ^4.17.4 - mkdirp: ^0.5.1 - source-map-support: ^0.4.15 - checksum: 75d5fe060e4850dbdbd5f56db2928cd0b6b6c93a65ba5f2a991465af4dc3f4adf46d575138f228b2169b1e25e3b4a7cdd16515a355fea41b873321bf56467583 +"buffer-xor@npm:^1.0.3": + version: 1.0.3 + resolution: "buffer-xor@npm:1.0.3" + checksum: 10c520df29d62fa6e785e2800e586a20fc4f6dfad84bcdbd12e1e8a83856de1cb75c7ebd7abe6d036bbfab738a6cf18a3ae9c8e5a2e2eb3167ca7399ce65373a languageName: node linkType: hard -"babel-runtime@npm:^5.8.34": - version: 5.8.38 - resolution: "babel-runtime@npm:5.8.38" +"buffer@npm:4.9.2": + version: 4.9.2 + resolution: "buffer@npm:4.9.2" dependencies: - core-js: ^1.0.0 - checksum: fdb063787bdb2c2983cf7a61d8ed6171f21e59ce15e4a567e8737bb2e5dad7fe19b810cd351ba6dea13b487163c4ba8d2420f13a6e2e737a921b1bc2fbec04a9 + base64-js: ^1.0.2 + ieee754: ^1.1.4 + isarray: ^1.0.0 + checksum: 8801bc1ba08539f3be70eee307a8b9db3d40f6afbfd3cf623ab7ef41dffff1d0a31de0addbe1e66e0ca5f7193eeb667bfb1ecad3647f8f1b0750de07c13295c3 languageName: node linkType: hard -"babel-runtime@npm:^6.18.0, babel-runtime@npm:^6.22.0, babel-runtime@npm:^6.26.0": - version: 6.26.0 - resolution: "babel-runtime@npm:6.26.0" +"buffer@npm:^5.0.5, buffer@npm:^5.5.0, buffer@npm:^5.6.0": + version: 5.7.1 + resolution: "buffer@npm:5.7.1" dependencies: - core-js: ^2.4.0 - regenerator-runtime: ^0.11.0 - checksum: 8aeade94665e67a73c1ccc10f6fd42ba0c689b980032b70929de7a6d9a12eb87ef51902733f8fefede35afea7a5c3ef7e916a64d503446c1eedc9e3284bd3d50 + base64-js: ^1.3.1 + ieee754: ^1.1.13 + checksum: e2cf8429e1c4c7b8cbd30834ac09bd61da46ce35f5c22a78e6c2f04497d6d25541b16881e30a019c6fd3154150650ccee27a308eff3e26229d788bbdeb08ab84 languageName: node linkType: hard -"babel-template@npm:^6.24.1, babel-template@npm:^6.26.0": - version: 6.26.0 - resolution: "babel-template@npm:6.26.0" +"buffer@npm:^6.0.1, buffer@npm:^6.0.3": + version: 6.0.3 + resolution: "buffer@npm:6.0.3" dependencies: - babel-runtime: ^6.26.0 - babel-traverse: ^6.26.0 - babel-types: ^6.26.0 - babylon: ^6.18.0 - lodash: ^4.17.4 - checksum: 028dd57380f09b5641b74874a19073c53c4fb3f1696e849575aae18f8c80eaf21db75209057db862f3b893ce2cd9b795d539efa591b58f4a0fb011df0a56fbed + base64-js: ^1.3.1 + ieee754: ^1.2.1 + checksum: 5ad23293d9a731e4318e420025800b42bf0d264004c0286c8cc010af7a270c7a0f6522e84f54b9ad65cbd6db20b8badbfd8d2ebf4f80fa03dab093b89e68c3f9 languageName: node linkType: hard -"babel-traverse@npm:^6.24.1, babel-traverse@npm:^6.26.0": - version: 6.26.0 - resolution: "babel-traverse@npm:6.26.0" +"bufferutil@npm:^4.0.1": + version: 4.0.7 + resolution: "bufferutil@npm:4.0.7" dependencies: - babel-code-frame: ^6.26.0 - babel-messages: ^6.23.0 - babel-runtime: ^6.26.0 - babel-types: ^6.26.0 - babylon: ^6.18.0 - debug: ^2.6.8 - globals: ^9.18.0 - invariant: ^2.2.2 - lodash: ^4.17.4 - checksum: fca037588d2791ae0409f1b7aa56075b798699cccc53ea04d82dd1c0f97b9e7ab17065f7dd3ecd69101d7874c9c8fd5e0f88fa53abbae1fe94e37e6b81ebcb8d + node-gyp: latest + node-gyp-build: ^4.3.0 + checksum: f75aa87e3d1b99b87a95f60a855e63f70af07b57fb8443e75a2ddfef2e47788d130fdd46e3a78fd7e0c10176082b26dfbed970c5b8632e1cc299cafa0e93ce45 languageName: node linkType: hard -"babel-types@npm:^6.19.0, babel-types@npm:^6.24.1, babel-types@npm:^6.26.0": - version: 6.26.0 - resolution: "babel-types@npm:6.26.0" +"busboy@npm:^1.6.0": + version: 1.6.0 + resolution: "busboy@npm:1.6.0" dependencies: - babel-runtime: ^6.26.0 - esutils: ^2.0.2 - lodash: ^4.17.4 - to-fast-properties: ^1.0.3 - checksum: d16b0fa86e9b0e4c2623be81d0a35679faff24dd2e43cde4ca58baf49f3e39415a011a889e6c2259ff09e1228e4c3a3db6449a62de59e80152fe1ce7398fde76 + streamsearch: ^1.1.0 + checksum: 32801e2c0164e12106bf236291a00795c3c4e4b709ae02132883fe8478ba2ae23743b11c5735a0aae8afe65ac4b6ca4568b91f0d9fed1fdbc32ede824a73746e languageName: node linkType: hard -"babelify@npm:^7.3.0": - version: 7.3.0 - resolution: "babelify@npm:7.3.0" - dependencies: - babel-core: ^6.0.14 - object-assign: ^4.0.0 - checksum: 4e169606ed0f2ff6f886d2367c72243d36b3b354490ccc916b913f6b4afd14102c91f771d71d485857feb134581dd48702f25431e19b5c7035f474f9898c3c2e +"bytes@npm:3.1.2": + version: 3.1.2 + resolution: "bytes@npm:3.1.2" + checksum: e4bcd3948d289c5127591fbedf10c0b639ccbf00243504e4e127374a15c3bc8eed0d28d4aaab08ff6f1cf2abc0cce6ba3085ed32f4f90e82a5683ce0014e1b6e languageName: node linkType: hard -"babylon@npm:^6.18.0": - version: 6.18.0 - resolution: "babylon@npm:6.18.0" - bin: - babylon: ./bin/babylon.js - checksum: 0777ae0c735ce1cbfc856d627589ed9aae212b84fb0c03c368b55e6c5d3507841780052808d0ad46e18a2ba516e93d55eeed8cd967f3b2938822dfeccfb2a16d +"cacache@npm:^15.2.0": + version: 15.3.0 + resolution: "cacache@npm:15.3.0" + dependencies: + "@npmcli/fs": ^1.0.0 + "@npmcli/move-file": ^1.0.1 + chownr: ^2.0.0 + fs-minipass: ^2.0.0 + glob: ^7.1.4 + infer-owner: ^1.0.4 + lru-cache: ^6.0.0 + minipass: ^3.1.1 + minipass-collect: ^1.0.2 + minipass-flush: ^1.0.5 + minipass-pipeline: ^1.2.2 + mkdirp: ^1.0.3 + p-map: ^4.0.0 + promise-inflight: ^1.0.1 + rimraf: ^3.0.2 + ssri: ^8.0.1 + tar: ^6.0.2 + unique-filename: ^1.1.1 + checksum: a07327c27a4152c04eb0a831c63c00390d90f94d51bb80624a66f4e14a6b6360bbf02a84421267bd4d00ca73ac9773287d8d7169e8d2eafe378d2ce140579db8 languageName: node linkType: hard -"backoff@npm:^2.5.0": - version: 2.5.0 - resolution: "backoff@npm:2.5.0" - dependencies: - precond: 0.2 - checksum: ccdcf2a26acd9379d0d4f09e3fb3b7ee34dee94f07ab74d1e38b38f89a3675d9f3cbebb142d9c61c655f4c9eb63f1d6ec28cebeb3dc9215efd8fe7cef92725b9 +"cacheable-lookup@npm:^5.0.3": + version: 5.0.4 + resolution: "cacheable-lookup@npm:5.0.4" + checksum: 763e02cf9196bc9afccacd8c418d942fc2677f22261969a4c2c2e760fa44a2351a81557bd908291c3921fe9beb10b976ba8fa50c5ca837c5a0dd945f16468f2d languageName: node linkType: hard -"balanced-match@npm:^1.0.0": - version: 1.0.2 - resolution: "balanced-match@npm:1.0.2" - checksum: 9706c088a283058a8a99e0bf91b0a2f75497f185980d9ffa8b304de1d9e58ebda7c72c07ebf01dadedaac5b2907b2c6f566f660d62bd336c3468e960403b9d65 +"cacheable-lookup@npm:^6.0.4": + version: 6.1.0 + resolution: "cacheable-lookup@npm:6.1.0" + checksum: 4e37afe897219b1035335b0765106a2c970ffa930497b43cac5000b860f3b17f48d004187279fae97e2e4cbf6a3693709b6d64af65279c7d6c8453321d36d118 languageName: node linkType: hard -"base-x@npm:^3.0.2, base-x@npm:^3.0.8": - version: 3.0.9 - resolution: "base-x@npm:3.0.9" +"cacheable-request@npm:^7.0.2": + version: 7.0.2 + resolution: "cacheable-request@npm:7.0.2" dependencies: - safe-buffer: ^5.0.1 - checksum: 957101d6fd09e1903e846fd8f69fd7e5e3e50254383e61ab667c725866bec54e5ece5ba49ce385128ae48f9ec93a26567d1d5ebb91f4d56ef4a9cc0d5a5481e8 + clone-response: ^1.0.2 + get-stream: ^5.1.0 + http-cache-semantics: ^4.0.0 + keyv: ^4.0.0 + lowercase-keys: ^2.0.0 + normalize-url: ^6.0.1 + responselike: ^2.0.0 + checksum: 6152813982945a5c9989cb457a6c499f12edcc7ade323d2fbfd759abc860bdbd1306e08096916bb413c3c47e812f8e4c0a0cc1e112c8ce94381a960f115bc77f languageName: node linkType: hard -"base64-js@npm:^1.0.2, base64-js@npm:^1.3.1": - version: 1.5.1 - resolution: "base64-js@npm:1.5.1" - checksum: 669632eb3745404c2f822a18fc3a0122d2f9a7a13f7fb8b5823ee19d1d2ff9ee5b52c53367176ea4ad093c332fd5ab4bd0ebae5a8e27917a4105a4cfc86b1005 +"call-bind@npm:^1.0.0, call-bind@npm:^1.0.2": + version: 1.0.2 + resolution: "call-bind@npm:1.0.2" + dependencies: + function-bind: ^1.1.1 + get-intrinsic: ^1.0.2 + checksum: f8e31de9d19988a4b80f3e704788c4a2d6b6f3d17cfec4f57dc29ced450c53a49270dc66bf0fbd693329ee948dd33e6c90a329519aef17474a4d961e8d6426b0 languageName: node linkType: hard -"base@npm:^0.11.1": - version: 0.11.2 - resolution: "base@npm:0.11.2" +"caller-callsite@npm:^2.0.0": + version: 2.0.0 + resolution: "caller-callsite@npm:2.0.0" dependencies: - cache-base: ^1.0.1 - class-utils: ^0.3.5 - component-emitter: ^1.2.1 - define-property: ^1.0.0 - isobject: ^3.0.1 - mixin-deep: ^1.2.0 - pascalcase: ^0.1.1 - checksum: a4a146b912e27eea8f66d09cb0c9eab666f32ce27859a7dfd50f38cd069a2557b39f16dba1bc2aecb3b44bf096738dd207b7970d99b0318423285ab1b1994edd + callsites: ^2.0.0 + checksum: b685e9d126d9247b320cfdfeb3bc8da0c4be28d8fb98c471a96bc51aab3130099898a2fe3bf0308f0fe048d64c37d6d09f563958b9afce1a1e5e63d879c128a2 languageName: node linkType: hard -"bcrypt-pbkdf@npm:^1.0.0": - version: 1.0.2 - resolution: "bcrypt-pbkdf@npm:1.0.2" +"caller-path@npm:^2.0.0": + version: 2.0.0 + resolution: "caller-path@npm:2.0.0" dependencies: - tweetnacl: ^0.14.3 - checksum: 4edfc9fe7d07019609ccf797a2af28351736e9d012c8402a07120c4453a3b789a15f2ee1530dc49eee8f7eb9379331a8dd4b3766042b9e502f74a68e7f662291 + caller-callsite: ^2.0.0 + checksum: 3e12ccd0c71ec10a057aac69e3ec175b721ca858c640df021ef0d25999e22f7c1d864934b596b7d47038e9b56b7ec315add042abbd15caac882998b50102fb12 languageName: node linkType: hard -"bech32@npm:1.1.4": - version: 1.1.4 - resolution: "bech32@npm:1.1.4" - checksum: 0e98db619191548390d6f09ff68b0253ba7ae6a55db93dfdbb070ba234c1fd3308c0606fbcc95fad50437227b10011e2698b89f0181f6e7f845c499bd14d0f4b +"callsites@npm:^2.0.0": + version: 2.0.0 + resolution: "callsites@npm:2.0.0" + checksum: be2f67b247df913732b7dec1ec0bbfcdbaea263e5a95968b19ec7965affae9496b970e3024317e6d4baa8e28dc6ba0cec03f46fdddc2fdcc51396600e53c2623 languageName: node linkType: hard -"bigint-crypto-utils@npm:^3.0.23": - version: 3.1.7 - resolution: "bigint-crypto-utils@npm:3.1.7" - dependencies: - bigint-mod-arith: ^3.1.0 - checksum: 10fa35d3e3d37639c8d501f45e0044c9062e7aa60783ae514e4d4ed3235ac24ac180e0dd0c77dad8cb5410ef24de42e1ea12527a997fec4c59f15fa83ea477ba +"callsites@npm:^3.0.0": + version: 3.1.0 + resolution: "callsites@npm:3.1.0" + checksum: 072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3 languageName: node linkType: hard -"bigint-mod-arith@npm:^3.1.0": - version: 3.1.2 - resolution: "bigint-mod-arith@npm:3.1.2" - checksum: badddd745f6e6c45674b22335d26a9ea83250e749abde20c5f84b24afbc747e259bc36798530953332349ed898f38ec39125b326cae8b8ee2dddfaea7ddf8448 +"camelcase@npm:^5.0.0": + version: 5.3.1 + resolution: "camelcase@npm:5.3.1" + checksum: e6effce26b9404e3c0f301498184f243811c30dfe6d0b9051863bd8e4034d09c8c2923794f280d6827e5aa055f6c434115ff97864a16a963366fb35fd673024b languageName: node linkType: hard -"bignumber.js@npm:^9.0.0": - version: 9.0.1 - resolution: "bignumber.js@npm:9.0.1" - checksum: 6e72f6069d9db32fc8d27561164de9f811b15f9144be61f323d8b36150a239eea50c92e20ba38af2ba5e717af10b8ef12db8f9948fe2ff02bf17ede5239d15d3 +"camelcase@npm:^6.0.0, camelcase@npm:^6.2.0": + version: 6.3.0 + resolution: "camelcase@npm:6.3.0" + checksum: 8c96818a9076434998511251dcb2761a94817ea17dbdc37f47ac080bd088fc62c7369429a19e2178b993497132c8cbcf5cc1f44ba963e76782ba469c0474938d languageName: node linkType: hard -"bignumber.js@npm:^9.1.0": - version: 9.1.1 - resolution: "bignumber.js@npm:9.1.1" - checksum: ad243b7e2f9120b112d670bb3d674128f0bd2ca1745b0a6c9df0433bd2c0252c43e6315d944c2ac07b4c639e7496b425e46842773cf89c6a2dcd4f31e5c4b11e +"cardinal@npm:^2.1.1": + version: 2.1.1 + resolution: "cardinal@npm:2.1.1" + dependencies: + ansicolors: ~0.3.2 + redeyed: ~2.1.0 + bin: + cdl: ./bin/cdl.js + checksum: e8d4ae46439cf8fed481c0efd267711ee91e199aa7821a9143e784ed94a6495accd01a0b36d84d377e8ee2cc9928a6c9c123b03be761c60b805f2c026b8a99ad languageName: node linkType: hard -"bignumber.js@npm:^9.1.2": - version: 9.3.1 - resolution: "bignumber.js@npm:9.3.1" - checksum: 6ab100271a23a75bb8b99a4b1a34a1a94967ac0b9a52a198147607bd91064e72c6f356380d7a09cd687bf50d81ad2ed1a0a8edfaa90369c9003ed8bb2440d7f0 +"caseless@npm:^0.12.0, caseless@npm:~0.12.0": + version: 0.12.0 + resolution: "caseless@npm:0.12.0" + checksum: b43bd4c440aa1e8ee6baefee8063b4850fd0d7b378f6aabc796c9ec8cb26d27fb30b46885350777d9bd079c5256c0e1329ad0dc7c2817e0bb466810ebb353751 languageName: node linkType: hard -"binary-extensions@npm:^2.0.0": - version: 2.2.0 - resolution: "binary-extensions@npm:2.2.0" - checksum: ccd267956c58d2315f5d3ea6757cf09863c5fc703e50fbeb13a7dc849b812ef76e3cf9ca8f35a0c48498776a7478d7b4a0418e1e2b8cb9cb9731f2922aaad7f8 +"cbor@npm:^8.1.0": + version: 8.1.0 + resolution: "cbor@npm:8.1.0" + dependencies: + nofilter: ^3.1.0 + checksum: a90338435dc7b45cc01461af979e3bb6ddd4f2a08584c437586039cd5f2235014c06e49d664295debbfb3514d87b2f06728092ab6aa6175e2e85e9cd7dc0c1fd languageName: node linkType: hard -"binary-install-raw@npm:0.0.13": - version: 0.0.13 - resolution: "binary-install-raw@npm:0.0.13" +"cbor@npm:^9.0.0": + version: 9.0.1 + resolution: "cbor@npm:9.0.1" dependencies: - axios: ^0.21.1 - rimraf: ^3.0.2 - tar: ^6.1.0 - checksum: f18515976237100459b4e2983832c941421ed8767c7fbc0ca716aa96210ccdd6c8ae9fdb9e0c39099248ebd8a3f4653560cb0b655192bb3b4efa1f7be204343a + nofilter: ^3.1.0 + checksum: 42333ac3d42cc3f6fcc7a529e68417a2dd8099eda43ca4be1304cdc5bc7494efe058e2db8a3d3b46ae60d69c7331ea813c22dbd019c4ac592d23e599d72bbcc9 languageName: node linkType: hard -"binaryen@npm:101.0.0-nightly.20210723": - version: 101.0.0-nightly.20210723 - resolution: "binaryen@npm:101.0.0-nightly.20210723" +"cborg@npm:^1.5.4, cborg@npm:^1.6.0": + version: 1.10.2 + resolution: "cborg@npm:1.10.2" bin: - wasm-opt: bin/wasm-opt - checksum: b1f7cc8e9fb4f1530e9454b5ea6deba17e2d863cea4efc6d0ba1b2af2325e9080c29df0ffeaf9708d455705a629a6a4fbef0ac29ed789a4e316b4c1437879f57 + cborg: cli.js + checksum: 7743a8f125046ac27fb371c4ea18af54fbe853f7210f1ffacc6504a79566480c39d52ac4fbc1a5b5155e27b13c3b58955dc29db1bf20c4d651549d55fec2fa7f languageName: node linkType: hard -"binaryen@npm:102.0.0-nightly.20211028": - version: 102.0.0-nightly.20211028 - resolution: "binaryen@npm:102.0.0-nightly.20211028" - bin: - wasm-opt: bin/wasm-opt - checksum: d360de0f21e35b73e868837278161ae0d3ccca4a2f87bd02c1cf28750ab355e3469a6a56664ca078f3ed5c2baade6575871b63cc61c9f98f101e55fbbe4ff024 +"chai-as-promised@npm:^7.1.1": + version: 7.1.1 + resolution: "chai-as-promised@npm:7.1.1" + dependencies: + check-error: ^1.0.2 + peerDependencies: + chai: ">= 2.1.2 < 5" + checksum: 7262868a5b51a12af4e432838ddf97a893109266a505808e1868ba63a12de7ee1166e9d43b5c501a190c377c1b11ecb9ff8e093c89f097ad96c397e8ec0f8d6a languageName: node linkType: hard -"binaryen@npm:111.0.0-nightly.20230202": - version: 111.0.0-nightly.20230202 - resolution: "binaryen@npm:111.0.0-nightly.20230202" - bin: - wasm-opt: bin/wasm-opt - wasm2js: bin/wasm2js - checksum: e57afd2c18e3498a25546dd093a100e5d12ac1bc57c6ef40cb2b8777baf2b31b9f6c2dd4be93296127b42bd8b064a86bba01db5b3ca737087b14668ff66a3c88 +"chai@npm:^4.3.4": + version: 4.3.6 + resolution: "chai@npm:4.3.6" + dependencies: + assertion-error: ^1.1.0 + check-error: ^1.0.2 + deep-eql: ^3.0.1 + get-func-name: ^2.0.0 + loupe: ^2.3.1 + pathval: ^1.1.1 + type-detect: ^4.0.5 + checksum: acff93fd537f96d4a4d62dd83810285dffcfccb5089e1bf2a1205b28ec82d93dff551368722893cf85004282df10ee68802737c33c90c5493957ed449ed7ce71 languageName: node linkType: hard -"bindings@npm:^1.5.0": - version: 1.5.0 - resolution: "bindings@npm:1.5.0" +"chalk@npm:3.0.0": + version: 3.0.0 + resolution: "chalk@npm:3.0.0" dependencies: - file-uri-to-path: 1.0.0 - checksum: 65b6b48095717c2e6105a021a7da4ea435aa8d3d3cd085cb9e85bcb6e5773cf318c4745c3f7c504412855940b585bdf9b918236612a1c7a7942491de176f1ae7 + ansi-styles: ^4.1.0 + supports-color: ^7.1.0 + checksum: 8e3ddf3981c4da405ddbd7d9c8d91944ddf6e33d6837756979f7840a29272a69a5189ecae0ff84006750d6d1e92368d413335eab4db5476db6e6703a1d1e0505 languageName: node linkType: hard -"bip39@npm:2.5.0": - version: 2.5.0 - resolution: "bip39@npm:2.5.0" +"chalk@npm:^1.0.0, chalk@npm:^1.1.0": + version: 1.1.3 + resolution: "chalk@npm:1.1.3" dependencies: - create-hash: ^1.1.0 - pbkdf2: ^3.0.9 - randombytes: ^2.0.1 - safe-buffer: ^5.0.1 - unorm: ^1.3.3 - checksum: 26e83583c43a8430afea1c385328b447005c74ddaf997cd8d3e416057f4968360b08ebf7de32374d605295c3abdd7ddd448d8078a2aa3d951735f4499c23875b + ansi-styles: ^2.2.1 + escape-string-regexp: ^1.0.2 + has-ansi: ^2.0.0 + strip-ansi: ^3.0.0 + supports-color: ^2.0.0 + checksum: 9d2ea6b98fc2b7878829eec223abcf404622db6c48396a9b9257f6d0ead2acf18231ae368d6a664a83f272b0679158da12e97b5229f794939e555cc574478acd languageName: node linkType: hard -"bl@npm:^1.0.0": - version: 1.2.3 - resolution: "bl@npm:1.2.3" +"chalk@npm:^2.0.0, chalk@npm:^2.1.0, chalk@npm:^2.4.2": + version: 2.4.2 + resolution: "chalk@npm:2.4.2" dependencies: - readable-stream: ^2.3.5 - safe-buffer: ^5.1.1 - checksum: 123f097989ce2fa9087ce761cd41176aaaec864e28f7dfe5c7dab8ae16d66d9844f849c3ad688eb357e3c5e4f49b573e3c0780bb8bc937206735a3b6f8569a5f + ansi-styles: ^3.2.1 + escape-string-regexp: ^1.0.5 + supports-color: ^5.3.0 + checksum: ec3661d38fe77f681200f878edbd9448821924e0f93a9cefc0e26a33b145f1027a2084bf19967160d11e1f03bfe4eaffcabf5493b89098b2782c3fe0b03d80c2 languageName: node linkType: hard -"bl@npm:^4.0.3": - version: 4.1.0 - resolution: "bl@npm:4.1.0" +"chalk@npm:^4, chalk@npm:^4.0.0, chalk@npm:^4.0.2, chalk@npm:^4.1.0, chalk@npm:^4.1.1, chalk@npm:^4.1.2": + version: 4.1.2 + resolution: "chalk@npm:4.1.2" dependencies: - buffer: ^5.5.0 - inherits: ^2.0.4 - readable-stream: ^3.4.0 - checksum: 9e8521fa7e83aa9427c6f8ccdcba6e8167ef30cc9a22df26effcc5ab682ef91d2cbc23a239f945d099289e4bbcfae7a192e9c28c84c6202e710a0dfec3722662 + ansi-styles: ^4.1.0 + supports-color: ^7.1.0 + checksum: fe75c9d5c76a7a98d45495b91b2172fa3b7a09e0cc9370e5c8feb1c567b85c4288e2b3fded7cfdd7359ac28d6b3844feb8b82b8686842e93d23c827c417e83fc languageName: node linkType: hard -"blakejs@npm:^1.1.0": - version: 1.1.1 - resolution: "blakejs@npm:1.1.1" - checksum: 77a0875af41fe0a6b15feacc69a4a730063df697b2932adbde15aa2c9c58a592870cd511a494ceee59cc8143ae64964dfa1bf301dab275b330debcd12c2b3db9 +"chardet@npm:^0.7.0": + version: 0.7.0 + resolution: "chardet@npm:0.7.0" + checksum: 6fd5da1f5d18ff5712c1e0aed41da200d7c51c28f11b36ee3c7b483f3696dabc08927fc6b227735eb8f0e1215c9a8abd8154637f3eff8cada5959df7f58b024d languageName: node linkType: hard -"blob-to-it@npm:^1.0.1": - version: 1.0.4 - resolution: "blob-to-it@npm:1.0.4" - dependencies: - browser-readablestream-to-it: ^1.0.3 - checksum: e7fbebe5bd7b8187a4a88203639777456596a0cc68372e7b2dbcfbae6dea2b80e2a89522140039b538140bc3e3a6b1e90d1778e725eb8899070f799e61591751 +"charenc@npm:>= 0.0.1": + version: 0.0.2 + resolution: "charenc@npm:0.0.2" + checksum: 81dcadbe57e861d527faf6dd3855dc857395a1c4d6781f4847288ab23cffb7b3ee80d57c15bba7252ffe3e5e8019db767757ee7975663ad2ca0939bb8fcaf2e5 languageName: node linkType: hard -"bluebird@npm:^3.5.0, bluebird@npm:^3.5.2": - version: 3.7.2 - resolution: "bluebird@npm:3.7.2" - checksum: 869417503c722e7dc54ca46715f70e15f4d9c602a423a02c825570862d12935be59ed9c7ba34a9b31f186c017c23cac6b54e35446f8353059c101da73eac22ef +"check-error@npm:^1.0.2": + version: 1.0.2 + resolution: "check-error@npm:1.0.2" + checksum: d9d106504404b8addd1ee3f63f8c0eaa7cd962a1a28eb9c519b1c4a1dc7098be38007fc0060f045ee00f075fbb7a2a4f42abcf61d68323677e11ab98dc16042e languageName: node linkType: hard -"bn.js@npm:4.11.6": - version: 4.11.6 - resolution: "bn.js@npm:4.11.6" - checksum: db23047bf06fdf9cf74401c8e76bca9f55313c81df382247d2c753868b368562e69171716b81b7038ada8860af18346fd4bcd1cf9d4963f923fe8e54e61cb58a +"chokidar@npm:3.3.0": + version: 3.3.0 + resolution: "chokidar@npm:3.3.0" + dependencies: + anymatch: ~3.1.1 + braces: ~3.0.2 + fsevents: ~2.1.1 + glob-parent: ~5.1.0 + is-binary-path: ~2.1.0 + is-glob: ~4.0.1 + normalize-path: ~3.0.0 + readdirp: ~3.2.0 + dependenciesMeta: + fsevents: + optional: true + checksum: e9863256ebb29dbc5e58a7e2637439814beb63b772686cb9e94478312c24dcaf3d0570220c5e75ea29029f43b664f9956d87b716120d38cf755f32124f047e8e languageName: node linkType: hard -"bn.js@npm:^4.0.0, bn.js@npm:^4.1.0, bn.js@npm:^4.10.0, bn.js@npm:^4.11.0, bn.js@npm:^4.11.6, bn.js@npm:^4.11.8, bn.js@npm:^4.11.9, bn.js@npm:^4.8.0": - version: 4.12.0 - resolution: "bn.js@npm:4.12.0" - checksum: 39afb4f15f4ea537b55eaf1446c896af28ac948fdcf47171961475724d1bb65118cca49fa6e3d67706e4790955ec0e74de584e45c8f1ef89f46c812bee5b5a12 +"chokidar@npm:3.5.3, chokidar@npm:^3.5.2": + version: 3.5.3 + resolution: "chokidar@npm:3.5.3" + dependencies: + anymatch: ~3.1.2 + braces: ~3.0.2 + fsevents: ~2.3.2 + glob-parent: ~5.1.2 + is-binary-path: ~2.1.0 + is-glob: ~4.0.1 + normalize-path: ~3.0.0 + readdirp: ~3.6.0 + dependenciesMeta: + fsevents: + optional: true + checksum: b49fcde40176ba007ff361b198a2d35df60d9bb2a5aab228279eb810feae9294a6b4649ab15981304447afe1e6ffbf4788ad5db77235dc770ab777c6e771980c languageName: node linkType: hard -"bn.js@npm:^5.0.0, bn.js@npm:^5.1.1, bn.js@npm:^5.1.3, bn.js@npm:^5.2.1": - version: 5.2.1 - resolution: "bn.js@npm:5.2.1" - checksum: 3dd8c8d38055fedfa95c1d5fc3c99f8dd547b36287b37768db0abab3c239711f88ff58d18d155dd8ad902b0b0cee973747b7ae20ea12a09473272b0201c9edd3 +"chokidar@npm:^3.5.3": + version: 3.6.0 + resolution: "chokidar@npm:3.6.0" + dependencies: + anymatch: ~3.1.2 + braces: ~3.0.2 + fsevents: ~2.3.2 + glob-parent: ~5.1.2 + is-binary-path: ~2.1.0 + is-glob: ~4.0.1 + normalize-path: ~3.0.0 + readdirp: ~3.6.0 + dependenciesMeta: + fsevents: + optional: true + checksum: d2f29f499705dcd4f6f3bbed79a9ce2388cf530460122eed3b9c48efeab7a4e28739c6551fd15bec9245c6b9eeca7a32baa64694d64d9b6faeb74ddb8c4a413d languageName: node linkType: hard -"bn.js@npm:^5.1.2, bn.js@npm:^5.2.0": - version: 5.2.0 - resolution: "bn.js@npm:5.2.0" - checksum: 6117170393200f68b35a061ecbf55d01dd989302e7b3c798a3012354fa638d124f0b2f79e63f77be5556be80322a09c40339eda6413ba7468524c0b6d4b4cb7a +"chokidar@npm:^4.0.0": + version: 4.0.3 + resolution: "chokidar@npm:4.0.3" + dependencies: + readdirp: ^4.0.1 + checksum: a8765e452bbafd04f3f2fad79f04222dd65f43161488bb6014a41099e6ca18d166af613d59a90771908c1c823efa3f46ba36b86ac50b701c20c1b9908c5fe36e languageName: node linkType: hard -"body-parser@npm:1.20.1, body-parser@npm:^1.16.0": - version: 1.20.1 - resolution: "body-parser@npm:1.20.1" - dependencies: - bytes: 3.1.2 - content-type: ~1.0.4 - debug: 2.6.9 - depd: 2.0.0 - destroy: 1.2.0 - http-errors: 2.0.0 - iconv-lite: 0.4.24 - on-finished: 2.4.1 - qs: 6.11.0 - raw-body: 2.5.1 - type-is: ~1.6.18 - unpipe: 1.0.0 - checksum: f1050dbac3bede6a78f0b87947a8d548ce43f91ccc718a50dd774f3c81f2d8b04693e52acf62659fad23101827dd318da1fb1363444ff9a8482b886a3e4a5266 +"chownr@npm:^1.0.1, chownr@npm:^1.1.1, chownr@npm:^1.1.4": + version: 1.1.4 + resolution: "chownr@npm:1.1.4" + checksum: 115648f8eb38bac5e41c3857f3e663f9c39ed6480d1349977c4d96c95a47266fcacc5a5aabf3cb6c481e22d72f41992827db47301851766c4fd77ac21a4f081d languageName: node linkType: hard -"brace-expansion@npm:^1.1.7": - version: 1.1.11 - resolution: "brace-expansion@npm:1.1.11" - dependencies: - balanced-match: ^1.0.0 - concat-map: 0.0.1 - checksum: faf34a7bb0c3fcf4b59c7808bc5d2a96a40988addf2e7e09dfbb67a2251800e0d14cd2bfc1aa79174f2f5095c54ff27f46fb1289fe2d77dac755b5eb3434cc07 +"chownr@npm:^2.0.0": + version: 2.0.0 + resolution: "chownr@npm:2.0.0" + checksum: c57cf9dd0791e2f18a5ee9c1a299ae6e801ff58fee96dc8bfd0dcb4738a6ce58dd252a3605b1c93c6418fe4f9d5093b28ffbf4d66648cb2a9c67eaef9679be2f languageName: node linkType: hard -"brace-expansion@npm:^2.0.1": - version: 2.0.1 - resolution: "brace-expansion@npm:2.0.1" - dependencies: - balanced-match: ^1.0.0 - checksum: a61e7cd2e8a8505e9f0036b3b6108ba5e926b4b55089eeb5550cd04a471fe216c96d4fe7e4c7f995c728c554ae20ddfc4244cad10aef255e72b62930afd233d1 +"ci-info@npm:^2.0.0": + version: 2.0.0 + resolution: "ci-info@npm:2.0.0" + checksum: 3b374666a85ea3ca43fa49aa3a048d21c9b475c96eb13c133505d2324e7ae5efd6a454f41efe46a152269e9b6a00c9edbe63ec7fa1921957165aae16625acd67 languageName: node linkType: hard -"braces@npm:^2.3.1": - version: 2.3.2 - resolution: "braces@npm:2.3.2" +"cids@npm:^0.7.1": + version: 0.7.5 + resolution: "cids@npm:0.7.5" dependencies: - arr-flatten: ^1.1.0 - array-unique: ^0.3.2 - extend-shallow: ^2.0.1 - fill-range: ^4.0.0 - isobject: ^3.0.1 - repeat-element: ^1.1.2 - snapdragon: ^0.8.1 - snapdragon-node: ^2.0.1 - split-string: ^3.0.2 - to-regex: ^3.0.1 - checksum: e30dcb6aaf4a31c8df17d848aa283a65699782f75ad61ae93ec25c9729c66cf58e66f0000a9fec84e4add1135bb7da40f7cb9601b36bebcfa9ca58e8d5c07de0 + buffer: ^5.5.0 + class-is: ^1.1.0 + multibase: ~0.6.0 + multicodec: ^1.0.0 + multihashes: ~0.4.15 + checksum: 54aa031bef76b08a2c934237696a4af2cfc8afb5d2727cb39ab69f6ac142ef312b9a0c6070dc2b4be0a43076d8961339d8bf85287773c647b3d1d25ce203f325 languageName: node linkType: hard -"braces@npm:^3.0.1, braces@npm:^3.0.2, braces@npm:~3.0.2": - version: 3.0.2 - resolution: "braces@npm:3.0.2" +"cipher-base@npm:^1.0.0, cipher-base@npm:^1.0.1, cipher-base@npm:^1.0.3": + version: 1.0.4 + resolution: "cipher-base@npm:1.0.4" dependencies: - fill-range: ^7.0.1 - checksum: e2a8e769a863f3d4ee887b5fe21f63193a891c68b612ddb4b68d82d1b5f3ff9073af066c343e9867a393fe4c2555dcb33e89b937195feb9c1613d259edfcd459 + inherits: ^2.0.1 + safe-buffer: ^5.0.1 + checksum: 47d3568dbc17431a339bad1fe7dff83ac0891be8206911ace3d3b818fc695f376df809bea406e759cdea07fff4b454fa25f1013e648851bec790c1d75763032e languageName: node linkType: hard -"brorand@npm:^1.0.1, brorand@npm:^1.1.0": +"class-is@npm:^1.1.0": version: 1.1.0 - resolution: "brorand@npm:1.1.0" - checksum: 8a05c9f3c4b46572dec6ef71012b1946db6cae8c7bb60ccd4b7dd5a84655db49fe043ecc6272e7ef1f69dc53d6730b9e2a3a03a8310509a3d797a618cbee52be + resolution: "class-is@npm:1.1.0" + checksum: 49024de3b264fc501a38dd59d8668f1a2b4973fa6fcef6b83d80fe6fe99a2000a8fbea5b50d4607169c65014843c9f6b41a4f8473df806c1b4787b4d47521880 languageName: node linkType: hard -"browser-level@npm:^1.0.1": - version: 1.0.1 - resolution: "browser-level@npm:1.0.1" - dependencies: - abstract-level: ^1.0.2 - catering: ^2.1.1 - module-error: ^1.0.2 - run-parallel-limit: ^1.1.0 - checksum: 67fbc77ce832940bfa25073eccff279f512ad56f545deb996a5b23b02316f5e76f4a79d381acc27eda983f5c9a2566aaf9c97e4fdd0748288c4407307537a29b +"clean-stack@npm:^2.0.0": + version: 2.2.0 + resolution: "clean-stack@npm:2.2.0" + checksum: 2ac8cd2b2f5ec986a3c743935ec85b07bc174d5421a5efc8017e1f146a1cf5f781ae962618f416352103b32c9cd7e203276e8c28241bbe946160cab16149fb68 languageName: node linkType: hard -"browser-readablestream-to-it@npm:^1.0.0, browser-readablestream-to-it@npm:^1.0.1, browser-readablestream-to-it@npm:^1.0.3": - version: 1.0.3 - resolution: "browser-readablestream-to-it@npm:1.0.3" - checksum: 07895bbc54cdeea62c8e9b7e32d374ec5c340ed1d0bc0c6cd6f1e0561ad931b160a3988426c763672ddf38ac1f75e45b9d8ae267b43f387183edafcad625f30a +"clean-stack@npm:^3.0.1": + version: 3.0.1 + resolution: "clean-stack@npm:3.0.1" + dependencies: + escape-string-regexp: 4.0.0 + checksum: dc18c842d7792dd72d463936b1b0a5b2621f0fc11588ee48b602e1a29b6c010c606d89f3de1f95d15d72de74aea93c0fbac8246593a31d95f8462cac36148e05 languageName: node linkType: hard -"browser-stdout@npm:1.3.1": - version: 1.3.1 - resolution: "browser-stdout@npm:1.3.1" - checksum: b717b19b25952dd6af483e368f9bcd6b14b87740c3d226c2977a65e84666ffd67000bddea7d911f111a9b6ddc822b234de42d52ab6507bce4119a4cc003ef7b3 +"cleaners@npm:^0.3.16": + version: 0.3.16 + resolution: "cleaners@npm:0.3.16" + checksum: f16873a26317b794a7e4f9eae4fe9ad86a96b404608b2d63f6ae1d4d4c4b7ea282c284ce8de539f52185db16eb44247bd097be044b053f88bbe4fdc46d9a2484 languageName: node linkType: hard -"browserify-aes@npm:^1.0.0, browserify-aes@npm:^1.0.4, browserify-aes@npm:^1.2.0": - version: 1.2.0 - resolution: "browserify-aes@npm:1.2.0" - dependencies: - buffer-xor: ^1.0.3 - cipher-base: ^1.0.0 - create-hash: ^1.1.0 - evp_bytestokey: ^1.0.3 - inherits: ^2.0.1 - safe-buffer: ^5.0.1 - checksum: 4a17c3eb55a2aa61c934c286f34921933086bf6d67f02d4adb09fcc6f2fc93977b47d9d884c25619144fccd47b3b3a399e1ad8b3ff5a346be47270114bcf7104 +"cli-boxes@npm:^2.2.1": + version: 2.2.1 + resolution: "cli-boxes@npm:2.2.1" + checksum: be79f8ec23a558b49e01311b39a1ea01243ecee30539c880cf14bf518a12e223ef40c57ead0cb44f509bffdffc5c129c746cd50d863ab879385370112af4f585 languageName: node linkType: hard -"browserify-cipher@npm:^1.0.0": - version: 1.0.1 - resolution: "browserify-cipher@npm:1.0.1" +"cli-cursor@npm:^1.0.1, cli-cursor@npm:^1.0.2": + version: 1.0.2 + resolution: "cli-cursor@npm:1.0.2" dependencies: - browserify-aes: ^1.0.4 - browserify-des: ^1.0.0 - evp_bytestokey: ^1.0.0 - checksum: 2d8500acf1ee535e6bebe808f7a20e4c3a9e2ed1a6885fff1facbfd201ac013ef030422bec65ca9ece8ffe82b03ca580421463f9c45af6c8415fd629f4118c13 + restore-cursor: ^1.0.1 + checksum: e3b4400d5e925ed11c7596f82e80e170693f69ac6f0f21da2a400043c37548dd780f985a1a5ef1ffb038e36fc6711d1d4f066b104eed851ae76e34bd883cf2bf languageName: node linkType: hard -"browserify-des@npm:^1.0.0": - version: 1.0.2 - resolution: "browserify-des@npm:1.0.2" +"cli-cursor@npm:^2.1.0": + version: 2.1.0 + resolution: "cli-cursor@npm:2.1.0" dependencies: - cipher-base: ^1.0.1 - des.js: ^1.0.0 - inherits: ^2.0.1 - safe-buffer: ^5.1.2 - checksum: b15a3e358a1d78a3b62ddc06c845d02afde6fc826dab23f1b9c016e643e7b1fda41de628d2110b712f6a44fb10cbc1800bc6872a03ddd363fb50768e010395b7 + restore-cursor: ^2.0.0 + checksum: d88e97bfdac01046a3ffe7d49f06757b3126559d7e44aa2122637eb179284dc6cd49fca2fac4f67c19faaf7e6dab716b6fe1dfcd309977407d8c7578ec2d044d languageName: node linkType: hard -"browserify-rsa@npm:^4.0.0, browserify-rsa@npm:^4.0.1": - version: 4.1.0 - resolution: "browserify-rsa@npm:4.1.0" +"cli-cursor@npm:^3.1.0": + version: 3.1.0 + resolution: "cli-cursor@npm:3.1.0" dependencies: - bn.js: ^5.0.0 - randombytes: ^2.0.1 - checksum: 155f0c135873efc85620571a33d884aa8810e40176125ad424ec9d85016ff105a07f6231650914a760cca66f29af0494087947b7be34880dd4599a0cd3c38e54 + restore-cursor: ^3.1.0 + checksum: 2692784c6cd2fd85cfdbd11f53aea73a463a6d64a77c3e098b2b4697a20443f430c220629e1ca3b195ea5ac4a97a74c2ee411f3807abf6df2b66211fec0c0a29 languageName: node linkType: hard -"browserify-sign@npm:^4.0.0": - version: 4.2.1 - resolution: "browserify-sign@npm:4.2.1" +"cli-progress@npm:^3.12.0": + version: 3.12.0 + resolution: "cli-progress@npm:3.12.0" dependencies: - bn.js: ^5.1.1 - browserify-rsa: ^4.0.1 - create-hash: ^1.2.0 - create-hmac: ^1.1.7 - elliptic: ^6.5.3 - inherits: ^2.0.4 - parse-asn1: ^5.1.5 - readable-stream: ^3.6.0 - safe-buffer: ^5.2.0 - checksum: 0221f190e3f5b2d40183fa51621be7e838d9caa329fe1ba773406b7637855f37b30f5d83e52ff8f244ed12ffe6278dd9983638609ed88c841ce547e603855707 + string-width: ^4.2.3 + checksum: e8390dc3cdf3c72ecfda0a1e8997bfed63a0d837f97366bbce0ca2ff1b452da386caed007b389f0fe972625037b6c8e7ab087c69d6184cc4dfc8595c4c1d3e6e languageName: node linkType: hard -"browserslist@npm:^3.2.6": - version: 3.2.8 - resolution: "browserslist@npm:3.2.8" - dependencies: - caniuse-lite: ^1.0.30000844 - electron-to-chromium: ^1.3.47 - bin: - browserslist: ./cli.js - checksum: 74d9ab1089a3813f54a7c4f9f6612faa6256799c8e42c7e00e4aae626c17f199049a01707a525a05b1673cd1493936583e51aad295e25249166e7e8fbd0273ba +"cli-spinners@npm:^2.2.0": + version: 2.6.1 + resolution: "cli-spinners@npm:2.6.1" + checksum: 423409baaa7a58e5104b46ca1745fbfc5888bbd0b0c5a626e052ae1387060839c8efd512fb127e25769b3dc9562db1dc1b5add6e0b93b7ef64f477feb6416a45 languageName: node linkType: hard -"bs58@npm:^4.0.0": - version: 4.0.1 - resolution: "bs58@npm:4.0.1" +"cli-table3@npm:0.6.0": + version: 0.6.0 + resolution: "cli-table3@npm:0.6.0" dependencies: - base-x: ^3.0.2 - checksum: b3c5365bb9e0c561e1a82f1a2d809a1a692059fae016be233a6127ad2f50a6b986467c3a50669ce4c18929dcccb297c5909314dd347a25a68c21b68eb3e95ac2 + colors: ^1.1.2 + object-assign: ^4.1.0 + string-width: ^4.2.0 + dependenciesMeta: + colors: + optional: true + checksum: 98682a2d3eef5ad07d34a08f90398d0640004e28ecf8eb59006436f11ed7b4d453db09f46c2ea880618fbd61fee66321b3b3ee1b20276bc708b6baf6f9663d75 languageName: node linkType: hard -"bs58check@npm:^2.1.2": - version: 2.1.2 - resolution: "bs58check@npm:2.1.2" +"cli-table3@npm:^0.5.0": + version: 0.5.1 + resolution: "cli-table3@npm:0.5.1" dependencies: - bs58: ^4.0.0 - create-hash: ^1.1.0 - safe-buffer: ^5.1.2 - checksum: 43bdf08a5dd04581b78f040bc4169480e17008da482ffe2a6507327bbc4fc5c28de0501f7faf22901cfe57fbca79cbb202ca529003fedb4cb8dccd265b38e54d + colors: ^1.1.2 + object-assign: ^4.1.0 + string-width: ^2.1.1 + dependenciesMeta: + colors: + optional: true + checksum: 3ff8c821440a2a0e655a01f04e5b54a0365b3814676cd93cec2b2b0b9952a08311797ad242a181733fcff714fa7d776f8bb45ad812f296390bfa5ef584fb231d languageName: node linkType: hard -"buffer-alloc-unsafe@npm:^1.1.0": - version: 1.1.0 - resolution: "buffer-alloc-unsafe@npm:1.1.0" - checksum: c5e18bf51f67754ec843c9af3d4c005051aac5008a3992938dda1344e5cfec77c4b02b4ca303644d1e9a6e281765155ce6356d85c6f5ccc5cd21afc868def396 +"cli-table3@npm:^0.6.0": + version: 0.6.3 + resolution: "cli-table3@npm:0.6.3" + dependencies: + "@colors/colors": 1.5.0 + string-width: ^4.2.0 + dependenciesMeta: + "@colors/colors": + optional: true + checksum: 09897f68467973f827c04e7eaadf13b55f8aec49ecd6647cc276386ea660059322e2dd8020a8b6b84d422dbdd619597046fa89cbbbdc95b2cea149a2df7c096c languageName: node linkType: hard -"buffer-alloc@npm:^1.2.0": - version: 1.2.0 - resolution: "buffer-alloc@npm:1.2.0" - dependencies: - buffer-alloc-unsafe: ^1.1.0 - buffer-fill: ^1.0.0 - checksum: 560cd27f3cbe73c614867da373407d4506309c62fe18de45a1ce191f3785ec6ca2488d802ff82065798542422980ca25f903db078c57822218182c37c3576df5 +"cli-width@npm:^1.0.1": + version: 1.1.1 + resolution: "cli-width@npm:1.1.1" + checksum: 24a3449ec8494aa900c635b988fb750007507af3d385a1aaff5edfb4db502d9686209578fe74215556bb2037523078660cd21ee5b35c2d8c0680a9d6d9b1e270 languageName: node linkType: hard -"buffer-fill@npm:^1.0.0": - version: 1.0.0 - resolution: "buffer-fill@npm:1.0.0" - checksum: c29b4723ddeab01e74b5d3b982a0c6828f2ded49cef049ddca3dac661c874ecdbcecb5dd8380cf0f4adbeb8cff90a7de724126750a1f1e5ebd4eb6c59a1315b1 +"cli-width@npm:^2.0.0": + version: 2.2.1 + resolution: "cli-width@npm:2.2.1" + checksum: 3c21b897a2ff551ae5b3c3ab32c866ed2965dcf7fb442f81adf0e27f4a397925c8f84619af7bcc6354821303f6ee9b2aa31d248306174f32c287986158cf4eed languageName: node linkType: hard -"buffer-from@npm:^1.0.0": - version: 1.1.2 - resolution: "buffer-from@npm:1.1.2" - checksum: 0448524a562b37d4d7ed9efd91685a5b77a50672c556ea254ac9a6d30e3403a517d8981f10e565db24e8339413b43c97ca2951f10e399c6125a0d8911f5679bb +"cliui@npm:^5.0.0": + version: 5.0.0 + resolution: "cliui@npm:5.0.0" + dependencies: + string-width: ^3.1.0 + strip-ansi: ^5.2.0 + wrap-ansi: ^5.1.0 + checksum: 0bb8779efe299b8f3002a73619eaa8add4081eb8d1c17bc4fedc6240557fb4eacdc08fe87c39b002eacb6cfc117ce736b362dbfd8bf28d90da800e010ee97df4 languageName: node linkType: hard -"buffer-to-arraybuffer@npm:^0.0.5": - version: 0.0.5 - resolution: "buffer-to-arraybuffer@npm:0.0.5" - checksum: b2e6493a6679e03d0e0e146b4258b9a6d92649d528d8fc4a74423b77f0d4f9398c9f965f3378d1683a91738054bae2761196cfe233f41ab3695126cb58cb25f9 +"cliui@npm:^7.0.2": + version: 7.0.4 + resolution: "cliui@npm:7.0.4" + dependencies: + string-width: ^4.2.0 + strip-ansi: ^6.0.0 + wrap-ansi: ^7.0.0 + checksum: ce2e8f578a4813806788ac399b9e866297740eecd4ad1823c27fd344d78b22c5f8597d548adbcc46f0573e43e21e751f39446c5a5e804a12aace402b7a315d7f languageName: node linkType: hard -"buffer-xor@npm:^1.0.3": +"clone-response@npm:^1.0.2": version: 1.0.3 - resolution: "buffer-xor@npm:1.0.3" - checksum: 10c520df29d62fa6e785e2800e586a20fc4f6dfad84bcdbd12e1e8a83856de1cb75c7ebd7abe6d036bbfab738a6cf18a3ae9c8e5a2e2eb3167ca7399ce65373a + resolution: "clone-response@npm:1.0.3" + dependencies: + mimic-response: ^1.0.0 + checksum: 4e671cac39b11c60aa8ba0a450657194a5d6504df51bca3fac5b3bd0145c4f8e8464898f87c8406b83232e3bc5cca555f51c1f9c8ac023969ebfbf7f6bdabb2e languageName: node linkType: hard -"buffer-xor@npm:^2.0.1": - version: 2.0.2 - resolution: "buffer-xor@npm:2.0.2" - dependencies: - safe-buffer: ^5.1.1 - checksum: 78226fcae9f4a0b4adec69dffc049f26f6bab240dfdd1b3f6fe07c4eb6b90da202ea5c363f98af676156ee39450a06405fddd9e8965f68a5327edcc89dcbe5d0 +"clone@npm:^1.0.2": + version: 1.0.4 + resolution: "clone@npm:1.0.4" + checksum: d06418b7335897209e77bdd430d04f882189582e67bd1f75a04565f3f07f5b3f119a9d670c943b6697d0afb100f03b866b3b8a1f91d4d02d72c4ecf2bb64b5dd languageName: node linkType: hard -"buffer@npm:4.9.2": - version: 4.9.2 - resolution: "buffer@npm:4.9.2" - dependencies: - base64-js: ^1.0.2 - ieee754: ^1.1.4 - isarray: ^1.0.0 - checksum: 8801bc1ba08539f3be70eee307a8b9db3d40f6afbfd3cf623ab7ef41dffff1d0a31de0addbe1e66e0ca5f7193eeb667bfb1ecad3647f8f1b0750de07c13295c3 +"code-point-at@npm:^1.0.0": + version: 1.1.0 + resolution: "code-point-at@npm:1.1.0" + checksum: 17d5666611f9b16d64fdf48176d9b7fb1c7d1c1607a189f7e600040a11a6616982876af148230336adb7d8fe728a559f743a4e29db3747e3b1a32fa7f4529681 languageName: node linkType: hard -"buffer@npm:^5.0.5, buffer@npm:^5.2.1, buffer@npm:^5.5.0, buffer@npm:^5.6.0": - version: 5.7.1 - resolution: "buffer@npm:5.7.1" +"color-convert@npm:^1.9.0": + version: 1.9.3 + resolution: "color-convert@npm:1.9.3" dependencies: - base64-js: ^1.3.1 - ieee754: ^1.1.13 - checksum: e2cf8429e1c4c7b8cbd30834ac09bd61da46ce35f5c22a78e6c2f04497d6d25541b16881e30a019c6fd3154150650ccee27a308eff3e26229d788bbdeb08ab84 + color-name: 1.1.3 + checksum: fd7a64a17cde98fb923b1dd05c5f2e6f7aefda1b60d67e8d449f9328b4e53b228a428fd38bfeaeb2db2ff6b6503a776a996150b80cdf224062af08a5c8a3a203 languageName: node linkType: hard -"buffer@npm:^6.0.1, buffer@npm:^6.0.3": - version: 6.0.3 - resolution: "buffer@npm:6.0.3" +"color-convert@npm:^2.0.1": + version: 2.0.1 + resolution: "color-convert@npm:2.0.1" dependencies: - base64-js: ^1.3.1 - ieee754: ^1.2.1 - checksum: 5ad23293d9a731e4318e420025800b42bf0d264004c0286c8cc010af7a270c7a0f6522e84f54b9ad65cbd6db20b8badbfd8d2ebf4f80fa03dab093b89e68c3f9 + color-name: ~1.1.4 + checksum: 79e6bdb9fd479a205c71d89574fccfb22bd9053bd98c6c4d870d65c132e5e904e6034978e55b43d69fcaa7433af2016ee203ce76eeba9cfa554b373e7f7db336 languageName: node linkType: hard -"bufferutil@npm:^4.0.1": - version: 4.0.7 - resolution: "bufferutil@npm:4.0.7" - dependencies: - node-gyp: latest - node-gyp-build: ^4.3.0 - checksum: f75aa87e3d1b99b87a95f60a855e63f70af07b57fb8443e75a2ddfef2e47788d130fdd46e3a78fd7e0c10176082b26dfbed970c5b8632e1cc299cafa0e93ce45 +"color-name@npm:1.1.3": + version: 1.1.3 + resolution: "color-name@npm:1.1.3" + checksum: 09c5d3e33d2105850153b14466501f2bfb30324a2f76568a408763a3b7433b0e50e5b4ab1947868e65cb101bb7cb75029553f2c333b6d4b8138a73fcc133d69d languageName: node linkType: hard -"busboy@npm:^1.6.0": - version: 1.6.0 - resolution: "busboy@npm:1.6.0" - dependencies: - streamsearch: ^1.1.0 - checksum: 32801e2c0164e12106bf236291a00795c3c4e4b709ae02132883fe8478ba2ae23743b11c5735a0aae8afe65ac4b6ca4568b91f0d9fed1fdbc32ede824a73746e +"color-name@npm:~1.1.4": + version: 1.1.4 + resolution: "color-name@npm:1.1.4" + checksum: b0445859521eb4021cd0fb0cc1a75cecf67fceecae89b63f62b201cca8d345baf8b952c966862a9d9a2632987d4f6581f0ec8d957dfacece86f0a7919316f610 languageName: node linkType: hard -"bytes@npm:3.1.2": - version: 3.1.2 - resolution: "bytes@npm:3.1.2" - checksum: e4bcd3948d289c5127591fbedf10c0b639ccbf00243504e4e127374a15c3bc8eed0d28d4aaab08ff6f1cf2abc0cce6ba3085ed32f4f90e82a5683ce0014e1b6e +"colors@npm:1.4.0, colors@npm:^1.1.2": + version: 1.4.0 + resolution: "colors@npm:1.4.0" + checksum: 98aa2c2418ad87dedf25d781be69dc5fc5908e279d9d30c34d8b702e586a0474605b3a189511482b9d5ed0d20c867515d22749537f7bc546256c6014f3ebdcec languageName: node linkType: hard -"bytewise-core@npm:^1.2.2": - version: 1.2.3 - resolution: "bytewise-core@npm:1.2.3" +"combined-stream@npm:^1.0.6, combined-stream@npm:^1.0.8, combined-stream@npm:~1.0.6": + version: 1.0.8 + resolution: "combined-stream@npm:1.0.8" dependencies: - typewise-core: ^1.2 - checksum: e0d28fb7ff5bb6fd9320eef31c6b37e98da3b9a24d9893e2c17e0ee544457e0c76c2d3fc642c99d82daa0f18dcd49e7dce8dcc338711200e9ced79107cb78e8e + delayed-stream: ~1.0.0 + checksum: 49fa4aeb4916567e33ea81d088f6584749fc90c7abec76fd516bf1c5aa5c79f3584b5ba3de6b86d26ddd64bae5329c4c7479343250cfe71c75bb366eae53bb7c languageName: node linkType: hard -"bytewise@npm:~1.1.0": - version: 1.1.0 - resolution: "bytewise@npm:1.1.0" - dependencies: - bytewise-core: ^1.2.2 - typewise: ^1.0.3 - checksum: 20d7387ecf8c29adc4740e626fb02eaa27f34ae4c5ca881657d403e792730c0625ba4fed824462b3ddb7d3ebe41b7abbfe24f1cd3bf07cecc5a631f154d2d8d2 +"command-exists@npm:^1.2.8": + version: 1.2.9 + resolution: "command-exists@npm:1.2.9" + checksum: 729ae3d88a2058c93c58840f30341b7f82688a573019535d198b57a4d8cb0135ced0ad7f52b591e5b28a90feb2c675080ce916e56254a0f7c15cb2395277cac3 languageName: node linkType: hard -"cacache@npm:^15.2.0": - version: 15.3.0 - resolution: "cacache@npm:15.3.0" +"command-line-args@npm:^5.1.1": + version: 5.2.1 + resolution: "command-line-args@npm:5.2.1" dependencies: - "@npmcli/fs": ^1.0.0 - "@npmcli/move-file": ^1.0.1 - chownr: ^2.0.0 - fs-minipass: ^2.0.0 - glob: ^7.1.4 - infer-owner: ^1.0.4 - lru-cache: ^6.0.0 - minipass: ^3.1.1 - minipass-collect: ^1.0.2 - minipass-flush: ^1.0.5 - minipass-pipeline: ^1.2.2 - mkdirp: ^1.0.3 - p-map: ^4.0.0 - promise-inflight: ^1.0.1 - rimraf: ^3.0.2 - ssri: ^8.0.1 - tar: ^6.0.2 - unique-filename: ^1.1.1 - checksum: a07327c27a4152c04eb0a831c63c00390d90f94d51bb80624a66f4e14a6b6360bbf02a84421267bd4d00ca73ac9773287d8d7169e8d2eafe378d2ce140579db8 + array-back: ^3.1.0 + find-replace: ^3.0.0 + lodash.camelcase: ^4.3.0 + typical: ^4.0.0 + checksum: e759519087be3cf2e86af8b9a97d3058b4910cd11ee852495be881a067b72891f6a32718fb685ee6d41531ab76b2b7bfb6602f79f882cd4b7587ff1e827982c7 languageName: node linkType: hard -"cache-base@npm:^1.0.1": - version: 1.0.1 - resolution: "cache-base@npm:1.0.1" +"command-line-usage@npm:^6.1.0": + version: 6.1.3 + resolution: "command-line-usage@npm:6.1.3" dependencies: - collection-visit: ^1.0.0 - component-emitter: ^1.2.1 - get-value: ^2.0.6 - has-value: ^1.0.0 - isobject: ^3.0.1 - set-value: ^2.0.0 - to-object-path: ^0.3.0 - union-value: ^1.0.0 - unset-value: ^1.0.0 - checksum: 9114b8654fe2366eedc390bad0bcf534e2f01b239a888894e2928cb58cdc1e6ea23a73c6f3450dcfd2058aa73a8a981e723cd1e7c670c047bf11afdc65880107 + array-back: ^4.0.2 + chalk: ^2.4.2 + table-layout: ^1.0.2 + typical: ^5.2.0 + checksum: 8261d4e5536eb0bcddee0ec5e89c05bb2abd18e5760785c8078ede5020bc1c612cbe28eb6586f5ed4a3660689748e5aaad4a72f21566f4ef39393694e2fa1a0b languageName: node linkType: hard -"cacheable-lookup@npm:^5.0.3": - version: 5.0.4 - resolution: "cacheable-lookup@npm:5.0.4" - checksum: 763e02cf9196bc9afccacd8c418d942fc2677f22261969a4c2c2e760fa44a2351a81557bd908291c3921fe9beb10b976ba8fa50c5ca837c5a0dd945f16468f2d +"commander@npm:2.18.0": + version: 2.18.0 + resolution: "commander@npm:2.18.0" + checksum: 3a31585348a5000bbdc457c9839aabbdf0bb0020e5dfaa1c9f9903680073d67c06911b55368e4c8df2ed166e0d4468f9a668585c1667c321804034a2819a819f languageName: node linkType: hard -"cacheable-lookup@npm:^6.0.4": - version: 6.1.0 - resolution: "cacheable-lookup@npm:6.1.0" - checksum: 4e37afe897219b1035335b0765106a2c970ffa930497b43cac5000b860f3b17f48d004187279fae97e2e4cbf6a3693709b6d64af65279c7d6c8453321d36d118 +"commander@npm:^2.20.3": + version: 2.20.3 + resolution: "commander@npm:2.20.3" + checksum: ab8c07884e42c3a8dbc5dd9592c606176c7eb5c1ca5ff274bcf907039b2c41de3626f684ea75ccf4d361ba004bbaff1f577d5384c155f3871e456bdf27becf9e languageName: node linkType: hard -"cacheable-request@npm:^6.0.0": - version: 6.1.0 - resolution: "cacheable-request@npm:6.1.0" - dependencies: - clone-response: ^1.0.2 - get-stream: ^5.1.0 - http-cache-semantics: ^4.0.0 - keyv: ^3.0.0 - lowercase-keys: ^2.0.0 - normalize-url: ^4.1.0 - responselike: ^1.0.2 - checksum: b510b237b18d17e89942e9ee2d2a077cb38db03f12167fd100932dfa8fc963424bfae0bfa1598df4ae16c944a5484e43e03df8f32105b04395ee9495e9e4e9f1 +"commander@npm:^8.1.0": + version: 8.3.0 + resolution: "commander@npm:8.3.0" + checksum: 0f82321821fc27b83bd409510bb9deeebcfa799ff0bf5d102128b500b7af22872c0c92cb6a0ebc5a4cf19c6b550fba9cedfa7329d18c6442a625f851377bacf0 languageName: node linkType: hard -"cacheable-request@npm:^7.0.2": - version: 7.0.2 - resolution: "cacheable-request@npm:7.0.2" - dependencies: - clone-response: ^1.0.2 - get-stream: ^5.1.0 - http-cache-semantics: ^4.0.0 - keyv: ^4.0.0 - lowercase-keys: ^2.0.0 - normalize-url: ^6.0.1 - responselike: ^2.0.0 - checksum: 6152813982945a5c9989cb457a6c499f12edcc7ade323d2fbfd759abc860bdbd1306e08096916bb413c3c47e812f8e4c0a0cc1e112c8ce94381a960f115bc77f +"compare-versions@npm:^6.0.0": + version: 6.1.0 + resolution: "compare-versions@npm:6.1.0" + checksum: d4e2a45706a023d8d0b6680338b66b79e20bd02d1947f0ac6531dab634cbed89fa373b3f03d503c5e489761194258d6e1bae67a07f88b1efc61648454f2d47e7 languageName: node linkType: hard -"cachedown@npm:1.0.0": - version: 1.0.0 - resolution: "cachedown@npm:1.0.0" - dependencies: - abstract-leveldown: ^2.4.1 - lru-cache: ^3.2.0 - checksum: ffd229839ca7efbfa14e35321fb8df444421e192bdf7be16048a303d2a24f3ed86cbe6c7a8cca91761423e4c53c3ed1098d337bbb9d3448801d4792172b4ab3e +"concat-map@npm:0.0.1": + version: 0.0.1 + resolution: "concat-map@npm:0.0.1" + checksum: 902a9f5d8967a3e2faf138d5cb784b9979bad2e6db5357c5b21c568df4ebe62bcb15108af1b2253744844eb964fc023fbd9afbbbb6ddd0bcc204c6fb5b7bf3af languageName: node linkType: hard -"call-bind@npm:^1.0.0, call-bind@npm:^1.0.2, call-bind@npm:~1.0.2": - version: 1.0.2 - resolution: "call-bind@npm:1.0.2" +"concat-stream@npm:^1.6.0, concat-stream@npm:^1.6.2, concat-stream@npm:~1.6.2": + version: 1.6.2 + resolution: "concat-stream@npm:1.6.2" dependencies: - function-bind: ^1.1.1 - get-intrinsic: ^1.0.2 - checksum: f8e31de9d19988a4b80f3e704788c4a2d6b6f3d17cfec4f57dc29ced450c53a49270dc66bf0fbd693329ee948dd33e6c90a329519aef17474a4d961e8d6426b0 + buffer-from: ^1.0.0 + inherits: ^2.0.3 + readable-stream: ^2.2.2 + typedarray: ^0.0.6 + checksum: 1ef77032cb4459dcd5187bd710d6fc962b067b64ec6a505810de3d2b8cc0605638551b42f8ec91edf6fcd26141b32ef19ad749239b58fae3aba99187adc32285 languageName: node linkType: hard -"caller-callsite@npm:^2.0.0": - version: 2.0.0 - resolution: "caller-callsite@npm:2.0.0" - dependencies: - callsites: ^2.0.0 - checksum: b685e9d126d9247b320cfdfeb3bc8da0c4be28d8fb98c471a96bc51aab3130099898a2fe3bf0308f0fe048d64c37d6d09f563958b9afce1a1e5e63d879c128a2 +"console-control-strings@npm:^1.0.0, console-control-strings@npm:~1.1.0": + version: 1.1.0 + resolution: "console-control-strings@npm:1.1.0" + checksum: 8755d76787f94e6cf79ce4666f0c5519906d7f5b02d4b884cf41e11dcd759ed69c57da0670afd9236d229a46e0f9cf519db0cd829c6dca820bb5a5c3def584ed languageName: node linkType: hard -"caller-path@npm:^2.0.0": - version: 2.0.0 - resolution: "caller-path@npm:2.0.0" +"content-disposition@npm:0.5.4": + version: 0.5.4 + resolution: "content-disposition@npm:0.5.4" dependencies: - caller-callsite: ^2.0.0 - checksum: 3e12ccd0c71ec10a057aac69e3ec175b721ca858c640df021ef0d25999e22f7c1d864934b596b7d47038e9b56b7ec315add042abbd15caac882998b50102fb12 + safe-buffer: 5.2.1 + checksum: afb9d545e296a5171d7574fcad634b2fdf698875f4006a9dd04a3e1333880c5c0c98d47b560d01216fb6505a54a2ba6a843ee3a02ec86d7e911e8315255f56c3 languageName: node linkType: hard -"callsites@npm:^2.0.0": - version: 2.0.0 - resolution: "callsites@npm:2.0.0" - checksum: be2f67b247df913732b7dec1ec0bbfcdbaea263e5a95968b19ec7965affae9496b970e3024317e6d4baa8e28dc6ba0cec03f46fdddc2fdcc51396600e53c2623 +"content-hash@npm:^2.5.2": + version: 2.5.2 + resolution: "content-hash@npm:2.5.2" + dependencies: + cids: ^0.7.1 + multicodec: ^0.5.5 + multihashes: ^0.4.15 + checksum: 31869e4d137b59d02003df0c0f0ad080744d878ed12a57f7d20b2cfd526d59d6317e9f52fa6e49cba59df7f9ab49ceb96d6a832685b85bae442e0c906f7193be languageName: node linkType: hard -"callsites@npm:^3.0.0": - version: 3.1.0 - resolution: "callsites@npm:3.1.0" - checksum: 072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3 +"content-type@npm:~1.0.4": + version: 1.0.4 + resolution: "content-type@npm:1.0.4" + checksum: 3d93585fda985d1554eca5ebd251994327608d2e200978fdbfba21c0c679914d5faf266d17027de44b34a72c7b0745b18584ecccaa7e1fdfb6a68ac7114f12e0 languageName: node linkType: hard -"camelcase@npm:^3.0.0": - version: 3.0.0 - resolution: "camelcase@npm:3.0.0" - checksum: ae4fe1c17c8442a3a345a6b7d2393f028ab7a7601af0c352ad15d1ab97ca75112e19e29c942b2a214898e160194829b68923bce30e018d62149c6d84187f1673 +"cookie-signature@npm:1.0.6": + version: 1.0.6 + resolution: "cookie-signature@npm:1.0.6" + checksum: f4e1b0a98a27a0e6e66fd7ea4e4e9d8e038f624058371bf4499cfcd8f3980be9a121486995202ba3fca74fbed93a407d6d54d43a43f96fd28d0bd7a06761591a languageName: node linkType: hard -"camelcase@npm:^5.0.0": - version: 5.3.1 - resolution: "camelcase@npm:5.3.1" - checksum: e6effce26b9404e3c0f301498184f243811c30dfe6d0b9051863bd8e4034d09c8c2923794f280d6827e5aa055f6c434115ff97864a16a963366fb35fd673024b +"cookie@npm:0.5.0": + version: 0.5.0 + resolution: "cookie@npm:0.5.0" + checksum: 1f4bd2ca5765f8c9689a7e8954183f5332139eb72b6ff783d8947032ec1fdf43109852c178e21a953a30c0dd42257828185be01b49d1eb1a67fd054ca588a180 languageName: node linkType: hard -"camelcase@npm:^6.0.0": - version: 6.3.0 - resolution: "camelcase@npm:6.3.0" - checksum: 8c96818a9076434998511251dcb2761a94817ea17dbdc37f47ac080bd088fc62c7369429a19e2178b993497132c8cbcf5cc1f44ba963e76782ba469c0474938d +"cookie@npm:^0.4.1": + version: 0.4.2 + resolution: "cookie@npm:0.4.2" + checksum: a00833c998bedf8e787b4c342defe5fa419abd96b32f4464f718b91022586b8f1bafbddd499288e75c037642493c83083da426c6a9080d309e3bd90fd11baa9b languageName: node linkType: hard -"caniuse-lite@npm:^1.0.30000844": - version: 1.0.30001425 - resolution: "caniuse-lite@npm:1.0.30001425" - checksum: 4fbf9f5b125b15a3eeaf7b75ca611f417ab9ce1a9fc07ee1023b2a7c0cc9844ad61ff089e814e4af6f747b9b532b6b50e7cb7844e6c29900f68ac9d171193ece +"core-js@npm:^1.0.0": + version: 1.2.7 + resolution: "core-js@npm:1.2.7" + checksum: 0b76371bfa98708351cde580f9287e2360d2209920e738ae950ae74ad08639a2e063541020bf666c28778956fc356ed9fe56d962129c88a87a6a4a0612526c75 languageName: node linkType: hard -"cardinal@npm:^2.1.1": - version: 2.1.1 - resolution: "cardinal@npm:2.1.1" - dependencies: - ansicolors: ~0.3.2 - redeyed: ~2.1.0 - bin: - cdl: ./bin/cdl.js - checksum: e8d4ae46439cf8fed481c0efd267711ee91e199aa7821a9143e784ed94a6495accd01a0b36d84d377e8ee2cc9928a6c9c123b03be761c60b805f2c026b8a99ad +"core-js@npm:^2.4.0, core-js@npm:^2.5.0": + version: 2.6.12 + resolution: "core-js@npm:2.6.12" + checksum: 44fa9934a85f8c78d61e0c8b7b22436330471ffe59ec5076fe7f324d6e8cf7f824b14b1c81ca73608b13bdb0fef035bd820989bf059767ad6fa13123bb8bd016 languageName: node linkType: hard -"case@npm:^1.6.3": - version: 1.6.3 - resolution: "case@npm:1.6.3" - checksum: febe73278f910b0d28aab7efd6f51c235f9aa9e296148edb56dfb83fd58faa88308c30ce9a0122b6e53e0362c44f4407105bd5ef89c46860fc2b184e540fd68d +"core-util-is@npm:1.0.2": + version: 1.0.2 + resolution: "core-util-is@npm:1.0.2" + checksum: 7a4c925b497a2c91421e25bf76d6d8190f0b2359a9200dbeed136e63b2931d6294d3b1893eda378883ed363cd950f44a12a401384c609839ea616befb7927dab languageName: node linkType: hard -"caseless@npm:^0.12.0, caseless@npm:~0.12.0": - version: 0.12.0 - resolution: "caseless@npm:0.12.0" - checksum: b43bd4c440aa1e8ee6baefee8063b4850fd0d7b378f6aabc796c9ec8cb26d27fb30b46885350777d9bd079c5256c0e1329ad0dc7c2817e0bb466810ebb353751 +"core-util-is@npm:~1.0.0": + version: 1.0.3 + resolution: "core-util-is@npm:1.0.3" + checksum: 9de8597363a8e9b9952491ebe18167e3b36e7707569eed0ebf14f8bba773611376466ae34575bca8cfe3c767890c859c74056084738f09d4e4a6f902b2ad7d99 languageName: node linkType: hard -"catering@npm:^2.1.0, catering@npm:^2.1.1": - version: 2.1.1 - resolution: "catering@npm:2.1.1" - checksum: 205daefa69c935b0c19f3d8f2e0a520dd69aebe9bda55902958003f7c9cff8f967dfb90071b421bd6eb618576f657a89d2bc0986872c9bc04bbd66655e9d4bd6 +"cors@npm:^2.8.1": + version: 2.8.5 + resolution: "cors@npm:2.8.5" + dependencies: + object-assign: ^4 + vary: ^1 + checksum: ced838404ccd184f61ab4fdc5847035b681c90db7ac17e428f3d81d69e2989d2b680cc254da0e2554f5ed4f8a341820a1ce3d1c16b499f6e2f47a1b9b07b5006 languageName: node linkType: hard -"cbor@npm:^8.1.0": - version: 8.1.0 - resolution: "cbor@npm:8.1.0" +"cosmiconfig@npm:7.0.1": + version: 7.0.1 + resolution: "cosmiconfig@npm:7.0.1" dependencies: - nofilter: ^3.1.0 - checksum: a90338435dc7b45cc01461af979e3bb6ddd4f2a08584c437586039cd5f2235014c06e49d664295debbfb3514d87b2f06728092ab6aa6175e2e85e9cd7dc0c1fd + "@types/parse-json": ^4.0.0 + import-fresh: ^3.2.1 + parse-json: ^5.0.0 + path-type: ^4.0.0 + yaml: ^1.10.0 + checksum: 4be63e7117955fd88333d7460e4c466a90f556df6ef34efd59034d2463484e339666c41f02b523d574a797ec61f4a91918c5b89a316db2ea2f834e0d2d09465b languageName: node linkType: hard -"cbor@npm:^9.0.0": - version: 9.0.1 - resolution: "cbor@npm:9.0.1" +"cosmiconfig@npm:^5.0.7": + version: 5.2.1 + resolution: "cosmiconfig@npm:5.2.1" dependencies: - nofilter: ^3.1.0 - checksum: 42333ac3d42cc3f6fcc7a529e68417a2dd8099eda43ca4be1304cdc5bc7494efe058e2db8a3d3b46ae60d69c7331ea813c22dbd019c4ac592d23e599d72bbcc9 + import-fresh: ^2.0.0 + is-directory: ^0.3.1 + js-yaml: ^3.13.1 + parse-json: ^4.0.0 + checksum: 8b6f1d3c8a5ffdf663a952f17af0761adf210b7a5933d0fe8988f3ca3a1f0e1e5cbbb74d5b419c15933dd2fdcaec31dbc5cc85cb8259a822342b93b529eff89c languageName: node linkType: hard -"cborg@npm:^1.5.4, cborg@npm:^1.6.0": - version: 1.10.2 - resolution: "cborg@npm:1.10.2" +"crc-32@npm:^1.2.0": + version: 1.2.2 + resolution: "crc-32@npm:1.2.2" bin: - cborg: cli.js - checksum: 7743a8f125046ac27fb371c4ea18af54fbe853f7210f1ffacc6504a79566480c39d52ac4fbc1a5b5155e27b13c3b58955dc29db1bf20c4d651549d55fec2fa7f + crc32: bin/crc32.njs + checksum: ad2d0ad0cbd465b75dcaeeff0600f8195b686816ab5f3ba4c6e052a07f728c3e70df2e3ca9fd3d4484dc4ba70586e161ca5a2334ec8bf5a41bf022a6103ff243 languageName: node linkType: hard -"chai-as-promised@npm:^7.1.1": - version: 7.1.1 - resolution: "chai-as-promised@npm:7.1.1" +"create-ecdh@npm:^4.0.0": + version: 4.0.4 + resolution: "create-ecdh@npm:4.0.4" dependencies: - check-error: ^1.0.2 - peerDependencies: - chai: ">= 2.1.2 < 5" - checksum: 7262868a5b51a12af4e432838ddf97a893109266a505808e1868ba63a12de7ee1166e9d43b5c501a190c377c1b11ecb9ff8e093c89f097ad96c397e8ec0f8d6a + bn.js: ^4.1.0 + elliptic: ^6.5.3 + checksum: 0dd7fca9711d09e152375b79acf1e3f306d1a25ba87b8ff14c2fd8e68b83aafe0a7dd6c4e540c9ffbdd227a5fa1ad9b81eca1f233c38bb47770597ba247e614b languageName: node linkType: hard -"chai@npm:^4.3.4": - version: 4.3.6 - resolution: "chai@npm:4.3.6" +"create-hash@npm:^1.1.0, create-hash@npm:^1.1.2, create-hash@npm:^1.2.0": + version: 1.2.0 + resolution: "create-hash@npm:1.2.0" dependencies: - assertion-error: ^1.1.0 - check-error: ^1.0.2 - deep-eql: ^3.0.1 - get-func-name: ^2.0.0 - loupe: ^2.3.1 - pathval: ^1.1.1 - type-detect: ^4.0.5 - checksum: acff93fd537f96d4a4d62dd83810285dffcfccb5089e1bf2a1205b28ec82d93dff551368722893cf85004282df10ee68802737c33c90c5493957ed449ed7ce71 + cipher-base: ^1.0.1 + inherits: ^2.0.1 + md5.js: ^1.3.4 + ripemd160: ^2.0.1 + sha.js: ^2.4.0 + checksum: 02a6ae3bb9cd4afee3fabd846c1d8426a0e6b495560a977ba46120c473cb283be6aa1cace76b5f927cf4e499c6146fb798253e48e83d522feba807d6b722eaa9 languageName: node linkType: hard -"chalk@npm:3.0.0": - version: 3.0.0 - resolution: "chalk@npm:3.0.0" +"create-hmac@npm:^1.1.0, create-hmac@npm:^1.1.4, create-hmac@npm:^1.1.7": + version: 1.1.7 + resolution: "create-hmac@npm:1.1.7" dependencies: - ansi-styles: ^4.1.0 - supports-color: ^7.1.0 - checksum: 8e3ddf3981c4da405ddbd7d9c8d91944ddf6e33d6837756979f7840a29272a69a5189ecae0ff84006750d6d1e92368d413335eab4db5476db6e6703a1d1e0505 + cipher-base: ^1.0.3 + create-hash: ^1.1.0 + inherits: ^2.0.1 + ripemd160: ^2.0.0 + safe-buffer: ^5.0.1 + sha.js: ^2.4.8 + checksum: ba12bb2257b585a0396108c72830e85f882ab659c3320c83584b1037f8ab72415095167ced80dc4ce8e446a8ecc4b2acf36d87befe0707d73b26cf9dc77440ed languageName: node linkType: hard -"chalk@npm:^1.0.0, chalk@npm:^1.1.0, chalk@npm:^1.1.3": - version: 1.1.3 - resolution: "chalk@npm:1.1.3" - dependencies: - ansi-styles: ^2.2.1 - escape-string-regexp: ^1.0.2 - has-ansi: ^2.0.0 - strip-ansi: ^3.0.0 - supports-color: ^2.0.0 - checksum: 9d2ea6b98fc2b7878829eec223abcf404622db6c48396a9b9257f6d0ead2acf18231ae368d6a664a83f272b0679158da12e97b5229f794939e555cc574478acd +"create-require@npm:^1.1.0": + version: 1.1.1 + resolution: "create-require@npm:1.1.1" + checksum: a9a1503d4390d8b59ad86f4607de7870b39cad43d929813599a23714831e81c520bddf61bcdd1f8e30f05fd3a2b71ae8538e946eb2786dc65c2bbc520f692eff languageName: node linkType: hard -"chalk@npm:^2.0.0, chalk@npm:^2.1.0, chalk@npm:^2.4.1, chalk@npm:^2.4.2": - version: 2.4.2 - resolution: "chalk@npm:2.4.2" +"cross-fetch@npm:^3.1.4": + version: 3.1.5 + resolution: "cross-fetch@npm:3.1.5" dependencies: - ansi-styles: ^3.2.1 - escape-string-regexp: ^1.0.5 - supports-color: ^5.3.0 - checksum: ec3661d38fe77f681200f878edbd9448821924e0f93a9cefc0e26a33b145f1027a2084bf19967160d11e1f03bfe4eaffcabf5493b89098b2782c3fe0b03d80c2 + node-fetch: 2.6.7 + checksum: f6b8c6ee3ef993ace6277fd789c71b6acf1b504fd5f5c7128df4ef2f125a429e29cd62dc8c127523f04a5f2fa4771ed80e3f3d9695617f441425045f505cf3bb languageName: node linkType: hard -"chalk@npm:^4, chalk@npm:^4.0.0, chalk@npm:^4.0.2, chalk@npm:^4.1.0, chalk@npm:^4.1.1, chalk@npm:^4.1.2": - version: 4.1.2 - resolution: "chalk@npm:4.1.2" +"cross-spawn@npm:7.0.3, cross-spawn@npm:^7.0.2, cross-spawn@npm:^7.0.3": + version: 7.0.3 + resolution: "cross-spawn@npm:7.0.3" dependencies: - ansi-styles: ^4.1.0 - supports-color: ^7.1.0 - checksum: fe75c9d5c76a7a98d45495b91b2172fa3b7a09e0cc9370e5c8feb1c567b85c4288e2b3fded7cfdd7359ac28d6b3844feb8b82b8686842e93d23c827c417e83fc + path-key: ^3.1.0 + shebang-command: ^2.0.0 + which: ^2.0.1 + checksum: 671cc7c7288c3a8406f3c69a3ae2fc85555c04169e9d611def9a675635472614f1c0ed0ef80955d5b6d4e724f6ced67f0ad1bb006c2ea643488fcfef994d7f52 languageName: node linkType: hard -"chardet@npm:^0.7.0": - version: 0.7.0 - resolution: "chardet@npm:0.7.0" - checksum: 6fd5da1f5d18ff5712c1e0aed41da200d7c51c28f11b36ee3c7b483f3696dabc08927fc6b227735eb8f0e1215c9a8abd8154637f3eff8cada5959df7f58b024d +"cross-spawn@npm:^6.0.5": + version: 6.0.5 + resolution: "cross-spawn@npm:6.0.5" + dependencies: + nice-try: ^1.0.4 + path-key: ^2.0.1 + semver: ^5.5.0 + shebang-command: ^1.2.0 + which: ^1.2.9 + checksum: f893bb0d96cd3d5751d04e67145bdddf25f99449531a72e82dcbbd42796bbc8268c1076c6b3ea51d4d455839902804b94bc45dfb37ecbb32ea8e54a6741c3ab9 languageName: node linkType: hard -"charenc@npm:>= 0.0.1": +"crypt@npm:>= 0.0.1": version: 0.0.2 - resolution: "charenc@npm:0.0.2" - checksum: 81dcadbe57e861d527faf6dd3855dc857395a1c4d6781f4847288ab23cffb7b3ee80d57c15bba7252ffe3e5e8019db767757ee7975663ad2ca0939bb8fcaf2e5 + resolution: "crypt@npm:0.0.2" + checksum: baf4c7bbe05df656ec230018af8cf7dbe8c14b36b98726939cef008d473f6fe7a4fad906cfea4062c93af516f1550a3f43ceb4d6615329612c6511378ed9fe34 languageName: node linkType: hard -"check-error@npm:^1.0.2": - version: 1.0.2 - resolution: "check-error@npm:1.0.2" - checksum: d9d106504404b8addd1ee3f63f8c0eaa7cd962a1a28eb9c519b1c4a1dc7098be38007fc0060f045ee00f075fbb7a2a4f42abcf61d68323677e11ab98dc16042e +"crypto-browserify@npm:3.12.0": + version: 3.12.0 + resolution: "crypto-browserify@npm:3.12.0" + dependencies: + browserify-cipher: ^1.0.0 + browserify-sign: ^4.0.0 + create-ecdh: ^4.0.0 + create-hash: ^1.1.0 + create-hmac: ^1.1.0 + diffie-hellman: ^5.0.0 + inherits: ^2.0.1 + pbkdf2: ^3.0.3 + public-encrypt: ^4.0.0 + randombytes: ^2.0.0 + randomfill: ^1.0.3 + checksum: c1609af82605474262f3eaa07daa0b2140026bd264ab316d4bf1170272570dbe02f0c49e29407fe0d3634f96c507c27a19a6765fb856fed854a625f9d15618e2 languageName: node linkType: hard -"checkpoint-store@npm:^1.1.0": - version: 1.1.0 - resolution: "checkpoint-store@npm:1.1.0" - dependencies: - functional-red-black-tree: ^1.0.1 - checksum: 94e921ccb222c7970615e8b2bcd956dbd52f15a1c397af0447dbdef8ecd32ffe342e394d39e55f2912278a460f3736de777b5b57a5baf229c0a6bd04d2465511 +"crypto-js@npm:4.1.1": + version: 4.1.1 + resolution: "crypto-js@npm:4.1.1" + checksum: b3747c12ee3a7632fab3b3e171ea50f78b182545f0714f6d3e7e2858385f0f4101a15f2517e033802ce9d12ba50a391575ff4638c9de3dd9b2c4bc47768d5425 languageName: node linkType: hard -"chokidar@npm:3.3.0": - version: 3.3.0 - resolution: "chokidar@npm:3.3.0" - dependencies: - anymatch: ~3.1.1 - braces: ~3.0.2 - fsevents: ~2.1.1 - glob-parent: ~5.1.0 - is-binary-path: ~2.1.0 - is-glob: ~4.0.1 - normalize-path: ~3.0.0 - readdirp: ~3.2.0 - dependenciesMeta: - fsevents: - optional: true - checksum: e9863256ebb29dbc5e58a7e2637439814beb63b772686cb9e94478312c24dcaf3d0570220c5e75ea29029f43b664f9956d87b716120d38cf755f32124f047e8e +"crypto-js@npm:4.2.0": + version: 4.2.0 + resolution: "crypto-js@npm:4.2.0" + checksum: f051666dbc077c8324777f44fbd3aaea2986f198fe85092535130d17026c7c2ccf2d23ee5b29b36f7a4a07312db2fae23c9094b644cc35f7858b1b4fcaf27774 languageName: node linkType: hard -"chokidar@npm:3.5.3, chokidar@npm:^3.4.0, chokidar@npm:^3.5.2": - version: 3.5.3 - resolution: "chokidar@npm:3.5.3" +"d@npm:1, d@npm:^1.0.1": + version: 1.0.1 + resolution: "d@npm:1.0.1" dependencies: - anymatch: ~3.1.2 - braces: ~3.0.2 - fsevents: ~2.3.2 - glob-parent: ~5.1.2 - is-binary-path: ~2.1.0 - is-glob: ~4.0.1 - normalize-path: ~3.0.0 - readdirp: ~3.6.0 - dependenciesMeta: - fsevents: - optional: true - checksum: b49fcde40176ba007ff361b198a2d35df60d9bb2a5aab228279eb810feae9294a6b4649ab15981304447afe1e6ffbf4788ad5db77235dc770ab777c6e771980c + es5-ext: ^0.10.50 + type: ^1.0.1 + checksum: 49ca0639c7b822db670de93d4fbce44b4aa072cd848c76292c9978a8cd0fff1028763020ff4b0f147bd77bfe29b4c7f82e0f71ade76b2a06100543cdfd948d19 languageName: node linkType: hard -"chownr@npm:^1.0.1, chownr@npm:^1.1.1, chownr@npm:^1.1.4": - version: 1.1.4 - resolution: "chownr@npm:1.1.4" - checksum: 115648f8eb38bac5e41c3857f3e663f9c39ed6480d1349977c4d96c95a47266fcacc5a5aabf3cb6c481e22d72f41992827db47301851766c4fd77ac21a4f081d +"dashdash@npm:^1.12.0": + version: 1.14.1 + resolution: "dashdash@npm:1.14.1" + dependencies: + assert-plus: ^1.0.0 + checksum: 3634c249570f7f34e3d34f866c93f866c5b417f0dd616275decae08147dcdf8fccfaa5947380ccfb0473998ea3a8057c0b4cd90c875740ee685d0624b2983598 languageName: node linkType: hard -"chownr@npm:^2.0.0": - version: 2.0.0 - resolution: "chownr@npm:2.0.0" - checksum: c57cf9dd0791e2f18a5ee9c1a299ae6e801ff58fee96dc8bfd0dcb4738a6ce58dd252a3605b1c93c6418fe4f9d5093b28ffbf4d66648cb2a9c67eaef9679be2f +"death@npm:^1.1.0": + version: 1.1.0 + resolution: "death@npm:1.1.0" + checksum: 8010ba9a320752f9580eb474985ed214572c0595cf83e92859e3c5a014a01fc8e8f2f2908b80b5f8bca9cb3f94adb546cf55810df6b80e282452e355cdce5aaa languageName: node linkType: hard -"ci-info@npm:^2.0.0": - version: 2.0.0 - resolution: "ci-info@npm:2.0.0" - checksum: 3b374666a85ea3ca43fa49aa3a048d21c9b475c96eb13c133505d2324e7ae5efd6a454f41efe46a152269e9b6a00c9edbe63ec7fa1921957165aae16625acd67 +"debug@npm:2.6.9, debug@npm:^2.2.0, debug@npm:^2.6.9": + version: 2.6.9 + resolution: "debug@npm:2.6.9" + dependencies: + ms: 2.0.0 + checksum: d2f51589ca66df60bf36e1fa6e4386b318c3f1e06772280eea5b1ae9fd3d05e9c2b7fd8a7d862457d00853c75b00451aa2d7459b924629ee385287a650f58fe6 languageName: node linkType: hard -"cids@npm:^0.7.1": - version: 0.7.5 - resolution: "cids@npm:0.7.5" +"debug@npm:3.2.6": + version: 3.2.6 + resolution: "debug@npm:3.2.6" dependencies: - buffer: ^5.5.0 - class-is: ^1.1.0 - multibase: ~0.6.0 - multicodec: ^1.0.0 - multihashes: ~0.4.15 - checksum: 54aa031bef76b08a2c934237696a4af2cfc8afb5d2727cb39ab69f6ac142ef312b9a0c6070dc2b4be0a43076d8961339d8bf85287773c647b3d1d25ce203f325 + ms: ^2.1.1 + checksum: 07bc8b3a13ef3cfa6c06baf7871dfb174c291e5f85dbf566f086620c16b9c1a0e93bb8f1935ebbd07a683249e7e30286f2966e2ef461e8fd17b1b60732062d6b languageName: node linkType: hard -"cipher-base@npm:^1.0.0, cipher-base@npm:^1.0.1, cipher-base@npm:^1.0.3": - version: 1.0.4 - resolution: "cipher-base@npm:1.0.4" +"debug@npm:4, debug@npm:4.3.3, debug@npm:^4.0.1, debug@npm:^4.1.0, debug@npm:^4.1.1, debug@npm:^4.3.1, debug@npm:^4.3.2": + version: 4.3.3 + resolution: "debug@npm:4.3.3" dependencies: - inherits: ^2.0.1 - safe-buffer: ^5.0.1 - checksum: 47d3568dbc17431a339bad1fe7dff83ac0891be8206911ace3d3b818fc695f376df809bea406e759cdea07fff4b454fa25f1013e648851bec790c1d75763032e + ms: 2.1.2 + peerDependenciesMeta: + supports-color: + optional: true + checksum: 14472d56fe4a94dbcfaa6dbed2dd3849f1d72ba78104a1a328047bb564643ca49df0224c3a17fa63533fd11dd3d4c8636cd861191232a2c6735af00cc2d4de16 languageName: node linkType: hard -"class-is@npm:^1.1.0": - version: 1.1.0 - resolution: "class-is@npm:1.1.0" - checksum: 49024de3b264fc501a38dd59d8668f1a2b4973fa6fcef6b83d80fe6fe99a2000a8fbea5b50d4607169c65014843c9f6b41a4f8473df806c1b4787b4d47521880 +"debug@npm:4.3.4, debug@npm:^4.3.4": + version: 4.3.4 + resolution: "debug@npm:4.3.4" + dependencies: + ms: 2.1.2 + peerDependenciesMeta: + supports-color: + optional: true + checksum: 3dbad3f94ea64f34431a9cbf0bafb61853eda57bff2880036153438f50fb5a84f27683ba0d8e5426bf41a8c6ff03879488120cf5b3a761e77953169c0600a708 languageName: node linkType: hard -"class-utils@npm:^0.3.5": - version: 0.3.6 - resolution: "class-utils@npm:0.3.6" +"debug@npm:^3.2.6, debug@npm:^3.2.7": + version: 3.2.7 + resolution: "debug@npm:3.2.7" dependencies: - arr-union: ^3.1.0 - define-property: ^0.2.5 - isobject: ^3.0.0 - static-extend: ^0.1.1 - checksum: be108900801e639e50f96a7e4bfa8867c753a7750a7603879f3981f8b0a89cba657497a2d5f40cd4ea557ff15d535a100818bb486baf6e26fe5d7872e75f1078 + ms: ^2.1.1 + checksum: b3d8c5940799914d30314b7c3304a43305fd0715581a919dacb8b3176d024a782062368405b47491516d2091d6462d4d11f2f4974a405048094f8bfebfa3071c languageName: node linkType: hard -"classic-level@npm:^1.2.0": - version: 1.2.0 - resolution: "classic-level@npm:1.2.0" +"debug@npm:^4.3.5": + version: 4.4.3 + resolution: "debug@npm:4.4.3" dependencies: - abstract-level: ^1.0.2 - catering: ^2.1.0 - module-error: ^1.0.1 - napi-macros: ~2.0.0 - node-gyp: latest - node-gyp-build: ^4.3.0 - checksum: 88ddd12f2192c2775107d5e462998ac01095cb0222ca01dc2be77d8dcbbf9883c4c0a0248529cceee40a2f1232c68027b1aca731da9f767ad8e9483cbd61dd37 + ms: ^2.1.3 + peerDependenciesMeta: + supports-color: + optional: true + checksum: 4805abd570e601acdca85b6aa3757186084a45cff9b2fa6eee1f3b173caa776b45f478b2a71a572d616d2010cea9211d0ac4a02a610e4c18ac4324bde3760834 languageName: node linkType: hard -"clean-stack@npm:^2.0.0": - version: 2.2.0 - resolution: "clean-stack@npm:2.2.0" - checksum: 2ac8cd2b2f5ec986a3c743935ec85b07bc174d5421a5efc8017e1f146a1cf5f781ae962618f416352103b32c9cd7e203276e8c28241bbe946160cab16149fb68 +"decamelize@npm:^1.2.0": + version: 1.2.0 + resolution: "decamelize@npm:1.2.0" + checksum: ad8c51a7e7e0720c70ec2eeb1163b66da03e7616d7b98c9ef43cce2416395e84c1e9548dd94f5f6ffecfee9f8b94251fc57121a8b021f2ff2469b2bae247b8aa languageName: node linkType: hard -"clean-stack@npm:^3.0.1": - version: 3.0.1 - resolution: "clean-stack@npm:3.0.1" - dependencies: - escape-string-regexp: 4.0.0 - checksum: dc18c842d7792dd72d463936b1b0a5b2621f0fc11588ee48b602e1a29b6c010c606d89f3de1f95d15d72de74aea93c0fbac8246593a31d95f8462cac36148e05 +"decamelize@npm:^4.0.0": + version: 4.0.0 + resolution: "decamelize@npm:4.0.0" + checksum: b7d09b82652c39eead4d6678bb578e3bebd848add894b76d0f6b395bc45b2d692fb88d977e7cfb93c4ed6c119b05a1347cef261174916c2e75c0a8ca57da1809 languageName: node linkType: hard -"cleaners@npm:^0.3.16": - version: 0.3.16 - resolution: "cleaners@npm:0.3.16" - checksum: f16873a26317b794a7e4f9eae4fe9ad86a96b404608b2d63f6ae1d4d4c4b7ea282c284ce8de539f52185db16eb44247bd097be044b053f88bbe4fdc46d9a2484 +"decode-uri-component@npm:^0.2.0": + version: 0.2.0 + resolution: "decode-uri-component@npm:0.2.0" + checksum: f3749344ab9305ffcfe4bfe300e2dbb61fc6359e2b736812100a3b1b6db0a5668cba31a05e4b45d4d63dbf1a18dfa354cd3ca5bb3ededddabb8cd293f4404f94 languageName: node linkType: hard -"cli-cursor@npm:^1.0.1, cli-cursor@npm:^1.0.2": - version: 1.0.2 - resolution: "cli-cursor@npm:1.0.2" - dependencies: - restore-cursor: ^1.0.1 - checksum: e3b4400d5e925ed11c7596f82e80e170693f69ac6f0f21da2a400043c37548dd780f985a1a5ef1ffb038e36fc6711d1d4f066b104eed851ae76e34bd883cf2bf - languageName: node - linkType: hard - -"cli-cursor@npm:^2.1.0": - version: 2.1.0 - resolution: "cli-cursor@npm:2.1.0" +"decompress-response@npm:^3.3.0": + version: 3.3.0 + resolution: "decompress-response@npm:3.3.0" dependencies: - restore-cursor: ^2.0.0 - checksum: d88e97bfdac01046a3ffe7d49f06757b3126559d7e44aa2122637eb179284dc6cd49fca2fac4f67c19faaf7e6dab716b6fe1dfcd309977407d8c7578ec2d044d + mimic-response: ^1.0.0 + checksum: 952552ac3bd7de2fc18015086b09468645c9638d98a551305e485230ada278c039c91116e946d07894b39ee53c0f0d5b6473f25a224029344354513b412d7380 languageName: node linkType: hard -"cli-cursor@npm:^3.1.0": - version: 3.1.0 - resolution: "cli-cursor@npm:3.1.0" +"decompress-response@npm:^6.0.0": + version: 6.0.0 + resolution: "decompress-response@npm:6.0.0" dependencies: - restore-cursor: ^3.1.0 - checksum: 2692784c6cd2fd85cfdbd11f53aea73a463a6d64a77c3e098b2b4697a20443f430c220629e1ca3b195ea5ac4a97a74c2ee411f3807abf6df2b66211fec0c0a29 + mimic-response: ^3.1.0 + checksum: d377cf47e02d805e283866c3f50d3d21578b779731e8c5072d6ce8c13cc31493db1c2f6784da9d1d5250822120cefa44f1deab112d5981015f2e17444b763812 languageName: node linkType: hard -"cli-progress@npm:^3.12.0": - version: 3.12.0 - resolution: "cli-progress@npm:3.12.0" +"deep-eql@npm:^3.0.1": + version: 3.0.1 + resolution: "deep-eql@npm:3.0.1" dependencies: - string-width: ^4.2.3 - checksum: e8390dc3cdf3c72ecfda0a1e8997bfed63a0d837f97366bbce0ca2ff1b452da386caed007b389f0fe972625037b6c8e7ab087c69d6184cc4dfc8595c4c1d3e6e - languageName: node - linkType: hard - -"cli-spinners@npm:^2.2.0": - version: 2.6.1 - resolution: "cli-spinners@npm:2.6.1" - checksum: 423409baaa7a58e5104b46ca1745fbfc5888bbd0b0c5a626e052ae1387060839c8efd512fb127e25769b3dc9562db1dc1b5add6e0b93b7ef64f477feb6416a45 + type-detect: ^4.0.0 + checksum: 4f4c9fb79eb994fb6e81d4aa8b063adc40c00f831588aa65e20857d5d52f15fb23034a6576ecf886f7ff6222d5ae42e71e9b7d57113e0715b1df7ea1e812b125 languageName: node linkType: hard -"cli-table3@npm:0.6.0": +"deep-extend@npm:^0.6.0, deep-extend@npm:~0.6.0": version: 0.6.0 - resolution: "cli-table3@npm:0.6.0" - dependencies: - colors: ^1.1.2 - object-assign: ^4.1.0 - string-width: ^4.2.0 - dependenciesMeta: - colors: - optional: true - checksum: 98682a2d3eef5ad07d34a08f90398d0640004e28ecf8eb59006436f11ed7b4d453db09f46c2ea880618fbd61fee66321b3b3ee1b20276bc708b6baf6f9663d75 + resolution: "deep-extend@npm:0.6.0" + checksum: 7be7e5a8d468d6b10e6a67c3de828f55001b6eb515d014f7aeb9066ce36bd5717161eb47d6a0f7bed8a9083935b465bc163ee2581c8b128d29bf61092fdf57a7 languageName: node linkType: hard -"cli-table3@npm:^0.5.0": - version: 0.5.1 - resolution: "cli-table3@npm:0.5.1" - dependencies: - colors: ^1.1.2 - object-assign: ^4.1.0 - string-width: ^2.1.1 - dependenciesMeta: - colors: - optional: true - checksum: 3ff8c821440a2a0e655a01f04e5b54a0365b3814676cd93cec2b2b0b9952a08311797ad242a181733fcff714fa7d776f8bb45ad812f296390bfa5ef584fb231d +"deep-is@npm:^0.1.3, deep-is@npm:~0.1.3": + version: 0.1.4 + resolution: "deep-is@npm:0.1.4" + checksum: edb65dd0d7d1b9c40b2f50219aef30e116cedd6fc79290e740972c132c09106d2e80aa0bc8826673dd5a00222d4179c84b36a790eef63a4c4bca75a37ef90804 languageName: node linkType: hard -"cli-table3@npm:^0.6.0": - version: 0.6.3 - resolution: "cli-table3@npm:0.6.3" +"defaults@npm:^1.0.3": + version: 1.0.3 + resolution: "defaults@npm:1.0.3" dependencies: - "@colors/colors": 1.5.0 - string-width: ^4.2.0 - dependenciesMeta: - "@colors/colors": - optional: true - checksum: 09897f68467973f827c04e7eaadf13b55f8aec49ecd6647cc276386ea660059322e2dd8020a8b6b84d422dbdd619597046fa89cbbbdc95b2cea149a2df7c096c + clone: ^1.0.2 + checksum: 96e2112da6553d376afd5265ea7cbdb2a3b45535965d71ab8bb1da10c8126d168fdd5268799625324b368356d21ba2a7b3d4ec50961f11a47b7feb9de3d4413e languageName: node linkType: hard -"cli-width@npm:^1.0.1": - version: 1.1.1 - resolution: "cli-width@npm:1.1.1" - checksum: 24a3449ec8494aa900c635b988fb750007507af3d385a1aaff5edfb4db502d9686209578fe74215556bb2037523078660cd21ee5b35c2d8c0680a9d6d9b1e270 +"defer-to-connect@npm:^2.0.0, defer-to-connect@npm:^2.0.1": + version: 2.0.1 + resolution: "defer-to-connect@npm:2.0.1" + checksum: 8a9b50d2f25446c0bfefb55a48e90afd58f85b21bcf78e9207cd7b804354f6409032a1705c2491686e202e64fc05f147aa5aa45f9aa82627563f045937f5791b languageName: node linkType: hard -"cli-width@npm:^2.0.0": - version: 2.2.1 - resolution: "cli-width@npm:2.2.1" - checksum: 3c21b897a2ff551ae5b3c3ab32c866ed2965dcf7fb442f81adf0e27f4a397925c8f84619af7bcc6354821303f6ee9b2aa31d248306174f32c287986158cf4eed +"define-data-property@npm:^1.0.1": + version: 1.1.0 + resolution: "define-data-property@npm:1.1.0" + dependencies: + get-intrinsic: ^1.2.1 + gopd: ^1.0.1 + has-property-descriptors: ^1.0.0 + checksum: 7ad4ee84cca8ad427a4831f5693526804b62ce9dfd4efac77214e95a4382aed930072251d4075dc8dc9fc949a353ed51f19f5285a84a788ba9216cc51472a093 languageName: node linkType: hard -"cliui@npm:^3.2.0": - version: 3.2.0 - resolution: "cliui@npm:3.2.0" +"define-properties@npm:^1.1.2, define-properties@npm:^1.1.4": + version: 1.1.4 + resolution: "define-properties@npm:1.1.4" dependencies: - string-width: ^1.0.1 - strip-ansi: ^3.0.1 - wrap-ansi: ^2.0.0 - checksum: c68d1dbc3e347bfe79ed19cc7f48007d5edd6cd8438342e32073e0b4e311e3c44e1f4f19221462bc6590de56c2df520e427533a9dde95dee25710bec322746ad + has-property-descriptors: ^1.0.0 + object-keys: ^1.1.1 + checksum: ce0aef3f9eb193562b5cfb79b2d2c86b6a109dfc9fdcb5f45d680631a1a908c06824ddcdb72b7573b54e26ace07f0a23420aaba0d5c627b34d2c1de8ef527e2b languageName: node linkType: hard -"cliui@npm:^5.0.0": - version: 5.0.0 - resolution: "cliui@npm:5.0.0" +"define-properties@npm:^1.1.3": + version: 1.1.3 + resolution: "define-properties@npm:1.1.3" dependencies: - string-width: ^3.1.0 - strip-ansi: ^5.2.0 - wrap-ansi: ^5.1.0 - checksum: 0bb8779efe299b8f3002a73619eaa8add4081eb8d1c17bc4fedc6240557fb4eacdc08fe87c39b002eacb6cfc117ce736b362dbfd8bf28d90da800e010ee97df4 + object-keys: ^1.0.12 + checksum: da80dba55d0cd76a5a7ab71ef6ea0ebcb7b941f803793e4e0257b384cb772038faa0c31659d244e82c4342edef841c1a1212580006a05a5068ee48223d787317 languageName: node linkType: hard -"cliui@npm:^7.0.2": - version: 7.0.4 - resolution: "cliui@npm:7.0.4" +"define-properties@npm:^1.2.0": + version: 1.2.1 + resolution: "define-properties@npm:1.2.1" dependencies: - string-width: ^4.2.0 - strip-ansi: ^6.0.0 - wrap-ansi: ^7.0.0 - checksum: ce2e8f578a4813806788ac399b9e866297740eecd4ad1823c27fd344d78b22c5f8597d548adbcc46f0573e43e21e751f39446c5a5e804a12aace402b7a315d7f + define-data-property: ^1.0.1 + has-property-descriptors: ^1.0.0 + object-keys: ^1.1.1 + checksum: b4ccd00597dd46cb2d4a379398f5b19fca84a16f3374e2249201992f36b30f6835949a9429669ee6b41b6e837205a163eadd745e472069e70dfc10f03e5fcc12 languageName: node linkType: hard -"clone-response@npm:^1.0.2": - version: 1.0.3 - resolution: "clone-response@npm:1.0.3" - dependencies: - mimic-response: ^1.0.0 - checksum: 4e671cac39b11c60aa8ba0a450657194a5d6504df51bca3fac5b3bd0145c4f8e8464898f87c8406b83232e3bc5cca555f51c1f9c8ac023969ebfbf7f6bdabb2e +"delay@npm:^5.0.0": + version: 5.0.0 + resolution: "delay@npm:5.0.0" + checksum: 62f151151ecfde0d9afbb8a6be37a6d103c4cb24f35a20ef3fe56f920b0d0d0bb02bc9c0a3084d0179ef669ca332b91155f2ee4d9854622cd2cdba5fc95285f9 languageName: node linkType: hard -"clone@npm:2.1.2, clone@npm:^2.0.0": - version: 2.1.2 - resolution: "clone@npm:2.1.2" - checksum: aaf106e9bc025b21333e2f4c12da539b568db4925c0501a1bf4070836c9e848c892fa22c35548ce0d1132b08bbbfa17a00144fe58fccdab6fa900fec4250f67d +"delayed-stream@npm:~1.0.0": + version: 1.0.0 + resolution: "delayed-stream@npm:1.0.0" + checksum: 46fe6e83e2cb1d85ba50bd52803c68be9bd953282fa7096f51fc29edd5d67ff84ff753c51966061e5ba7cb5e47ef6d36a91924eddb7f3f3483b1c560f77a0020 languageName: node linkType: hard -"clone@npm:^1.0.2": - version: 1.0.4 - resolution: "clone@npm:1.0.4" - checksum: d06418b7335897209e77bdd430d04f882189582e67bd1f75a04565f3f07f5b3f119a9d670c943b6697d0afb100f03b866b3b8a1f91d4d02d72c4ecf2bb64b5dd +"delegates@npm:^1.0.0": + version: 1.0.0 + resolution: "delegates@npm:1.0.0" + checksum: a51744d9b53c164ba9c0492471a1a2ffa0b6727451bdc89e31627fdf4adda9d51277cfcbfb20f0a6f08ccb3c436f341df3e92631a3440226d93a8971724771fd languageName: node linkType: hard -"code-point-at@npm:^1.0.0": - version: 1.1.0 - resolution: "code-point-at@npm:1.1.0" - checksum: 17d5666611f9b16d64fdf48176d9b7fb1c7d1c1607a189f7e600040a11a6616982876af148230336adb7d8fe728a559f743a4e29db3747e3b1a32fa7f4529681 +"depd@npm:2.0.0": + version: 2.0.0 + resolution: "depd@npm:2.0.0" + checksum: abbe19c768c97ee2eed6282d8ce3031126662252c58d711f646921c9623f9052e3e1906443066beec1095832f534e57c523b7333f8e7e0d93051ab6baef5ab3a languageName: node linkType: hard -"collection-visit@npm:^1.0.0": - version: 1.0.0 - resolution: "collection-visit@npm:1.0.0" - dependencies: - map-visit: ^1.0.0 - object-visit: ^1.0.0 - checksum: 15d9658fe6eb23594728346adad5433b86bb7a04fd51bbab337755158722f9313a5376ef479de5b35fbc54140764d0d39de89c339f5d25b959ed221466981da9 +"depd@npm:^1.1.2": + version: 1.1.2 + resolution: "depd@npm:1.1.2" + checksum: 6b406620d269619852885ce15965272b829df6f409724415e0002c8632ab6a8c0a08ec1f0bd2add05dc7bd7507606f7e2cc034fa24224ab829580040b835ecd9 languageName: node linkType: hard -"color-convert@npm:^1.9.0": - version: 1.9.3 - resolution: "color-convert@npm:1.9.3" +"des.js@npm:^1.0.0": + version: 1.0.1 + resolution: "des.js@npm:1.0.1" dependencies: - color-name: 1.1.3 - checksum: fd7a64a17cde98fb923b1dd05c5f2e6f7aefda1b60d67e8d449f9328b4e53b228a428fd38bfeaeb2db2ff6b6503a776a996150b80cdf224062af08a5c8a3a203 + inherits: ^2.0.1 + minimalistic-assert: ^1.0.0 + checksum: 1ec2eedd7ed6bd61dd5e0519fd4c96124e93bb22de8a9d211b02d63e5dd152824853d919bb2090f965cc0e3eb9c515950a9836b332020d810f9c71feb0fd7df4 languageName: node linkType: hard -"color-convert@npm:^2.0.1": - version: 2.0.1 - resolution: "color-convert@npm:2.0.1" - dependencies: - color-name: ~1.1.4 - checksum: 79e6bdb9fd479a205c71d89574fccfb22bd9053bd98c6c4d870d65c132e5e904e6034978e55b43d69fcaa7433af2016ee203ce76eeba9cfa554b373e7f7db336 +"destroy@npm:1.2.0": + version: 1.2.0 + resolution: "destroy@npm:1.2.0" + checksum: 0acb300b7478a08b92d810ab229d5afe0d2f4399272045ab22affa0d99dbaf12637659411530a6fcd597a9bdac718fc94373a61a95b4651bbc7b83684a565e38 languageName: node linkType: hard -"color-name@npm:1.1.3": - version: 1.1.3 - resolution: "color-name@npm:1.1.3" - checksum: 09c5d3e33d2105850153b14466501f2bfb30324a2f76568a408763a3b7433b0e50e5b4ab1947868e65cb101bb7cb75029553f2c333b6d4b8138a73fcc133d69d +"detect-libc@npm:^2.0.0": + version: 2.0.2 + resolution: "detect-libc@npm:2.0.2" + checksum: 2b2cd3649b83d576f4be7cc37eb3b1815c79969c8b1a03a40a4d55d83bc74d010753485753448eacb98784abf22f7dbd3911fd3b60e29fda28fed2d1a997944d languageName: node linkType: hard -"color-name@npm:~1.1.4": - version: 1.1.4 - resolution: "color-name@npm:1.1.4" - checksum: b0445859521eb4021cd0fb0cc1a75cecf67fceecae89b63f62b201cca8d345baf8b952c966862a9d9a2632987d4f6581f0ec8d957dfacece86f0a7919316f610 +"diff@npm:3.5.0": + version: 3.5.0 + resolution: "diff@npm:3.5.0" + checksum: 00842950a6551e26ce495bdbce11047e31667deea546527902661f25cc2e73358967ebc78cf86b1a9736ec3e14286433225f9970678155753a6291c3bca5227b languageName: node linkType: hard -"colors@npm:1.4.0, colors@npm:^1.1.2": - version: 1.4.0 - resolution: "colors@npm:1.4.0" - checksum: 98aa2c2418ad87dedf25d781be69dc5fc5908e279d9d30c34d8b702e586a0474605b3a189511482b9d5ed0d20c867515d22749537f7bc546256c6014f3ebdcec +"diff@npm:5.0.0": + version: 5.0.0 + resolution: "diff@npm:5.0.0" + checksum: f19fe29284b633afdb2725c2a8bb7d25761ea54d321d8e67987ac851c5294be4afeab532bd84531e02583a3fe7f4014aa314a3eda84f5590e7a9e6b371ef3b46 languageName: node linkType: hard -"combined-stream@npm:^1.0.6, combined-stream@npm:^1.0.8, combined-stream@npm:~1.0.6": - version: 1.0.8 - resolution: "combined-stream@npm:1.0.8" - dependencies: - delayed-stream: ~1.0.0 - checksum: 49fa4aeb4916567e33ea81d088f6584749fc90c7abec76fd516bf1c5aa5c79f3584b5ba3de6b86d26ddd64bae5329c4c7479343250cfe71c75bb366eae53bb7c +"diff@npm:^4.0.1": + version: 4.0.2 + resolution: "diff@npm:4.0.2" + checksum: f2c09b0ce4e6b301c221addd83bf3f454c0bc00caa3dd837cf6c127d6edf7223aa2bbe3b688feea110b7f262adbfc845b757c44c8a9f8c0c5b15d8fa9ce9d20d languageName: node linkType: hard -"command-exists@npm:^1.2.8": - version: 1.2.9 - resolution: "command-exists@npm:1.2.9" - checksum: 729ae3d88a2058c93c58840f30341b7f82688a573019535d198b57a4d8cb0135ced0ad7f52b591e5b28a90feb2c675080ce916e56254a0f7c15cb2395277cac3 +"diff@npm:^5.2.0": + version: 5.2.2 + resolution: "diff@npm:5.2.2" + checksum: a1af5d6322ca6312279369665b5a9e6d54cd2aed42729a30523e174ccd14661a752bf10d75deec8763964cab3df3787fe816f88e9de7ee8fe774852007269d88 languageName: node linkType: hard -"command-line-args@npm:^4.0.7": - version: 4.0.7 - resolution: "command-line-args@npm:4.0.7" +"diffie-hellman@npm:^5.0.0": + version: 5.0.3 + resolution: "diffie-hellman@npm:5.0.3" dependencies: - array-back: ^2.0.0 - find-replace: ^1.0.3 - typical: ^2.6.1 - bin: - command-line-args: bin/cli.js - checksum: 618109143fbca741048d54a5d31a2a5e166fbda318ed1419c1ca66877ce92ed80d6768a52a2e6392eb751f16ca7755d4014ced6f5f858a68d0cbe793bab6e3ee + bn.js: ^4.1.0 + miller-rabin: ^4.0.0 + randombytes: ^2.0.0 + checksum: 0e620f322170c41076e70181dd1c24e23b08b47dbb92a22a644f3b89b6d3834b0f8ee19e37916164e5eb1ee26d2aa836d6129f92723995267250a0b541811065 languageName: node linkType: hard -"command-line-args@npm:^5.1.1": - version: 5.2.1 - resolution: "command-line-args@npm:5.2.1" +"difflib@npm:^0.2.4": + version: 0.2.4 + resolution: "difflib@npm:0.2.4" dependencies: - array-back: ^3.1.0 - find-replace: ^3.0.0 - lodash.camelcase: ^4.3.0 - typical: ^4.0.0 - checksum: e759519087be3cf2e86af8b9a97d3058b4910cd11ee852495be881a067b72891f6a32718fb685ee6d41531ab76b2b7bfb6602f79f882cd4b7587ff1e827982c7 + heap: ">= 0.2.0" + checksum: 4f4237b026263ce7471b77d9019b901c2f358a7da89401a80a84a8c3cdc1643a8e70b7495ccbe686cb4d95492eaf5dac119cd9ecbffe5f06bfc175fbe5c20a27 languageName: node linkType: hard -"command-line-usage@npm:^6.1.0": - version: 6.1.3 - resolution: "command-line-usage@npm:6.1.3" +"dir-glob@npm:^3.0.1": + version: 3.0.1 + resolution: "dir-glob@npm:3.0.1" dependencies: - array-back: ^4.0.2 - chalk: ^2.4.2 - table-layout: ^1.0.2 - typical: ^5.2.0 - checksum: 8261d4e5536eb0bcddee0ec5e89c05bb2abd18e5760785c8078ede5020bc1c612cbe28eb6586f5ed4a3660689748e5aaad4a72f21566f4ef39393694e2fa1a0b + path-type: ^4.0.0 + checksum: fa05e18324510d7283f55862f3161c6759a3f2f8dbce491a2fc14c8324c498286c54282c1f0e933cb930da8419b30679389499b919122952a4f8592362ef4615 languageName: node linkType: hard -"commander@npm:2.18.0": - version: 2.18.0 - resolution: "commander@npm:2.18.0" - checksum: 3a31585348a5000bbdc457c9839aabbdf0bb0020e5dfaa1c9f9903680073d67c06911b55368e4c8df2ed166e0d4468f9a668585c1667c321804034a2819a819f +"disklet@npm:^0.4.5": + version: 0.4.6 + resolution: "disklet@npm:0.4.6" + dependencies: + rfc4648: ^1.3.0 + checksum: 2fc9e781b05edb1f9bce10a6aa9c00e90fb291f66c84837dcedd7b49fe7fd9449d5ee53e8009edcbf54c68dbd9119c65539eab2a8b4b0178a4c53252deb4056f languageName: node linkType: hard -"commander@npm:3.0.2": - version: 3.0.2 - resolution: "commander@npm:3.0.2" - checksum: 6d14ad030d1904428139487ed31febcb04c1604db2b8d9fae711f60ee6718828dc0e11602249e91c8a97b0e721e9c6d53edbc166bad3cde1596851d59a8f824d +"disklet@npm:^0.5.0": + version: 0.5.2 + resolution: "disklet@npm:0.5.2" + dependencies: + rfc4648: ^1.3.0 + checksum: 87c78fd781c6ecbcee1f095327857b7c74b8b8dcc305ebb97312367523b50a2bf6c3499615c5345bfc15210e384816d6a4cfd109081c3059a48479d3acf01012 languageName: node linkType: hard -"commander@npm:^2.20.3": - version: 2.20.3 - resolution: "commander@npm:2.20.3" - checksum: ab8c07884e42c3a8dbc5dd9592c606176c7eb5c1ca5ff274bcf907039b2c41de3626f684ea75ccf4d361ba004bbaff1f577d5384c155f3871e456bdf27becf9e +"dns-over-http-resolver@npm:^1.2.3": + version: 1.2.3 + resolution: "dns-over-http-resolver@npm:1.2.3" + dependencies: + debug: ^4.3.1 + native-fetch: ^3.0.0 + receptacle: ^1.3.2 + checksum: 3cc1a1d77fc43e7a8a12453da987b80860ac96dc1031386c5eb1a39154775a87cfa1d50c0eaa5ea5e397e898791654608f6e2acf03f750f4098ab8822bb7d928 languageName: node linkType: hard -"commander@npm:^8.1.0": - version: 8.3.0 - resolution: "commander@npm:8.3.0" - checksum: 0f82321821fc27b83bd409510bb9deeebcfa799ff0bf5d102128b500b7af22872c0c92cb6a0ebc5a4cf19c6b550fba9cedfa7329d18c6442a625f851377bacf0 +"docker-compose@npm:0.23.19": + version: 0.23.19 + resolution: "docker-compose@npm:0.23.19" + dependencies: + yaml: ^1.10.2 + checksum: 1704825954ec8645e4b099cc2641531955eef5a8a9729c885fab7067ae4d7935c663252e51b49878397e51cd5a3efcf2f13c8460e252aa39d14a0722c0bacfe5 languageName: node linkType: hard -"compare-versions@npm:^6.0.0": - version: 6.1.0 - resolution: "compare-versions@npm:6.1.0" - checksum: d4e2a45706a023d8d0b6680338b66b79e20bd02d1947f0ac6531dab634cbed89fa373b3f03d503c5e489761194258d6e1bae67a07f88b1efc61648454f2d47e7 +"docker-modem@npm:^1.0.8": + version: 1.0.9 + resolution: "docker-modem@npm:1.0.9" + dependencies: + JSONStream: 1.3.2 + debug: ^3.2.6 + readable-stream: ~1.0.26-4 + split-ca: ^1.0.0 + checksum: b34829f5abecf28332f1870c88bdf795750520264e9fdc8e9041058f18b1846543061ee32fb21ff14e9da6b5498af6b2cb4d96422d8c2dc02d9f622b01f34fe6 languageName: node linkType: hard -"component-emitter@npm:^1.2.1": - version: 1.3.0 - resolution: "component-emitter@npm:1.3.0" - checksum: b3c46de38ffd35c57d1c02488355be9f218e582aec72d72d1b8bbec95a3ac1b38c96cd6e03ff015577e68f550fbb361a3bfdbd9bb248be9390b7b3745691be6b +"dockerode@npm:2.5.8": + version: 2.5.8 + resolution: "dockerode@npm:2.5.8" + dependencies: + concat-stream: ~1.6.2 + docker-modem: ^1.0.8 + tar-fs: ~1.16.3 + checksum: 01381da98f98a3236b735fb2bb2a66f521da39200a2a11b83777cee3b104b32966ba7dfeb93f3fa8ab85b5e639265842d66f576e7db9562b1049564c2af6ec84 languageName: node linkType: hard -"concat-map@npm:0.0.1": - version: 0.0.1 - resolution: "concat-map@npm:0.0.1" - checksum: 902a9f5d8967a3e2faf138d5cb784b9979bad2e6db5357c5b21c568df4ebe62bcb15108af1b2253744844eb964fc023fbd9afbbbb6ddd0bcc204c6fb5b7bf3af +"doctrine@npm:^2.1.0": + version: 2.1.0 + resolution: "doctrine@npm:2.1.0" + dependencies: + esutils: ^2.0.2 + checksum: a45e277f7feaed309fe658ace1ff286c6e2002ac515af0aaf37145b8baa96e49899638c7cd47dccf84c3d32abfc113246625b3ac8f552d1046072adee13b0dc8 languageName: node linkType: hard -"concat-stream@npm:^1.5.1, concat-stream@npm:^1.6.0, concat-stream@npm:^1.6.2, concat-stream@npm:~1.6.2": - version: 1.6.2 - resolution: "concat-stream@npm:1.6.2" +"doctrine@npm:^3.0.0": + version: 3.0.0 + resolution: "doctrine@npm:3.0.0" dependencies: - buffer-from: ^1.0.0 - inherits: ^2.0.3 - readable-stream: ^2.2.2 - typedarray: ^0.0.6 - checksum: 1ef77032cb4459dcd5187bd710d6fc962b067b64ec6a505810de3d2b8cc0605638551b42f8ec91edf6fcd26141b32ef19ad749239b58fae3aba99187adc32285 + esutils: ^2.0.2 + checksum: fd7673ca77fe26cd5cba38d816bc72d641f500f1f9b25b83e8ce28827fe2da7ad583a8da26ab6af85f834138cf8dae9f69b0cd6ab925f52ddab1754db44d99ce languageName: node linkType: hard -"console-control-strings@npm:^1.0.0, console-control-strings@npm:~1.1.0": - version: 1.1.0 - resolution: "console-control-strings@npm:1.1.0" - checksum: 8755d76787f94e6cf79ce4666f0c5519906d7f5b02d4b884cf41e11dcd759ed69c57da0670afd9236d229a46e0f9cf519db0cd829c6dca820bb5a5c3def584ed +"dom-walk@npm:^0.1.0": + version: 0.1.2 + resolution: "dom-walk@npm:0.1.2" + checksum: 19eb0ce9c6de39d5e231530685248545d9cd2bd97b2cb3486e0bfc0f2a393a9addddfd5557463a932b52fdfcf68ad2a619020cd2c74a5fe46fbecaa8e80872f3 languageName: node linkType: hard -"content-disposition@npm:0.5.4": - version: 0.5.4 - resolution: "content-disposition@npm:0.5.4" - dependencies: - safe-buffer: 5.2.1 - checksum: afb9d545e296a5171d7574fcad634b2fdf698875f4006a9dd04a3e1333880c5c0c98d47b560d01216fb6505a54a2ba6a843ee3a02ec86d7e911e8315255f56c3 +"dotenv@npm:^10.0.0": + version: 10.0.0 + resolution: "dotenv@npm:10.0.0" + checksum: f412c5fe8c24fbe313d302d2500e247ba8a1946492db405a4de4d30dd0eb186a88a43f13c958c5a7de303938949c4231c56994f97d05c4bc1f22478d631b4005 languageName: node linkType: hard -"content-hash@npm:^2.5.2": - version: 2.5.2 - resolution: "content-hash@npm:2.5.2" +"ecc-jsbn@npm:~0.1.1": + version: 0.1.2 + resolution: "ecc-jsbn@npm:0.1.2" dependencies: - cids: ^0.7.1 - multicodec: ^0.5.5 - multihashes: ^0.4.15 - checksum: 31869e4d137b59d02003df0c0f0ad080744d878ed12a57f7d20b2cfd526d59d6317e9f52fa6e49cba59df7f9ab49ceb96d6a832685b85bae442e0c906f7193be + jsbn: ~0.1.0 + safer-buffer: ^2.1.0 + checksum: 22fef4b6203e5f31d425f5b711eb389e4c6c2723402e389af394f8411b76a488fa414d309d866e2b577ce3e8462d344205545c88a8143cc21752a5172818888a languageName: node linkType: hard -"content-type@npm:~1.0.4": - version: 1.0.4 - resolution: "content-type@npm:1.0.4" - checksum: 3d93585fda985d1554eca5ebd251994327608d2e200978fdbfba21c0c679914d5faf266d17027de44b34a72c7b0745b18584ecccaa7e1fdfb6a68ac7114f12e0 +"ee-first@npm:1.1.1": + version: 1.1.1 + resolution: "ee-first@npm:1.1.1" + checksum: 1b4cac778d64ce3b582a7e26b218afe07e207a0f9bfe13cc7395a6d307849cfe361e65033c3251e00c27dd060cab43014c2d6b2647676135e18b77d2d05b3f4f languageName: node linkType: hard -"convert-source-map@npm:^1.5.1": - version: 1.9.0 - resolution: "convert-source-map@npm:1.9.0" - checksum: dc55a1f28ddd0e9485ef13565f8f756b342f9a46c4ae18b843fe3c30c675d058d6a4823eff86d472f187b176f0adf51ea7b69ea38be34be4a63cbbf91b0593c8 +"eip55@npm:^2.1.1": + version: 2.1.1 + resolution: "eip55@npm:2.1.1" + dependencies: + keccak: ^3.0.3 + checksum: 512d319e4f91ab0c33b514f371206956521dcdcdd23e8eb4d6f9c21e3be9f72287c0b82feb854d3a1eec91805804d13c31e7a1a7dafd37f69eb9994a9c6c8f32 languageName: node linkType: hard -"cookie-signature@npm:1.0.6": - version: 1.0.6 - resolution: "cookie-signature@npm:1.0.6" - checksum: f4e1b0a98a27a0e6e66fd7ea4e4e9d8e038f624058371bf4499cfcd8f3980be9a121486995202ba3fca74fbed93a407d6d54d43a43f96fd28d0bd7a06761591a +"ejs@npm:3.1.6": + version: 3.1.6 + resolution: "ejs@npm:3.1.6" + dependencies: + jake: ^10.6.1 + bin: + ejs: ./bin/cli.js + checksum: 81a9cdea0b4ded3b5a4b212b7c17e20bb07468f08394e2d519708d367957a70aef3d282a6d5d38bf6ad313ba25802b9193d4227f29b084d2ee0f28d115141d48 languageName: node linkType: hard -"cookie@npm:0.5.0": - version: 0.5.0 - resolution: "cookie@npm:0.5.0" - checksum: 1f4bd2ca5765f8c9689a7e8954183f5332139eb72b6ff783d8947032ec1fdf43109852c178e21a953a30c0dd42257828185be01b49d1eb1a67fd054ca588a180 +"ejs@npm:^3.1.8": + version: 3.1.9 + resolution: "ejs@npm:3.1.9" + dependencies: + jake: ^10.8.5 + bin: + ejs: bin/cli.js + checksum: af6f10eb815885ff8a8cfacc42c6b6cf87daf97a4884f87a30e0c3271fedd85d76a3a297d9c33a70e735b97ee632887f85e32854b9cdd3a2d97edf931519a35f languageName: node linkType: hard -"cookie@npm:^0.4.1": - version: 0.4.2 - resolution: "cookie@npm:0.4.2" - checksum: a00833c998bedf8e787b4c342defe5fa419abd96b32f4464f718b91022586b8f1bafbddd499288e75c037642493c83083da426c6a9080d309e3bd90fd11baa9b +"electron-fetch@npm:^1.7.2": + version: 1.9.1 + resolution: "electron-fetch@npm:1.9.1" + dependencies: + encoding: ^0.1.13 + checksum: 33b5d363b9a234288e847237ef34536bd415f31cba3b1c69b2ae4679a2bae66fb7ded2b576b90a0b7cd240e3df71cf16f2b961d4ab82864df02b6b53cf49f05c languageName: node linkType: hard -"cookiejar@npm:^2.1.1": - version: 2.1.3 - resolution: "cookiejar@npm:2.1.3" - checksum: 88259983ebc52ceb23cdacfa48762b6a518a57872eff1c7ed01d214fff5cf492e2660d7d5c04700a28f1787a76811df39e8639f8e17670b3cf94ecd86e161f07 +"elliptic@npm:6.5.4, elliptic@npm:^6.4.0, elliptic@npm:^6.5.2, elliptic@npm:^6.5.3": + version: 6.5.4 + resolution: "elliptic@npm:6.5.4" + dependencies: + bn.js: ^4.11.9 + brorand: ^1.1.0 + hash.js: ^1.0.0 + hmac-drbg: ^1.0.1 + inherits: ^2.0.4 + minimalistic-assert: ^1.0.1 + minimalistic-crypto-utils: ^1.0.1 + checksum: d56d21fd04e97869f7ffcc92e18903b9f67f2d4637a23c860492fbbff5a3155fd9ca0184ce0c865dd6eb2487d234ce9551335c021c376cd2d3b7cb749c7d10f4 languageName: node linkType: hard -"copy-descriptor@npm:^0.1.0": - version: 0.1.1 - resolution: "copy-descriptor@npm:0.1.1" - checksum: d4b7b57b14f1d256bb9aa0b479241048afd7f5bcf22035fc7b94e8af757adeae247ea23c1a774fe44869fd5694efba4a969b88d966766c5245fdee59837fe45b +"elliptic@npm:6.6.1": + version: 6.6.1 + resolution: "elliptic@npm:6.6.1" + dependencies: + bn.js: ^4.11.9 + brorand: ^1.1.0 + hash.js: ^1.0.0 + hmac-drbg: ^1.0.1 + inherits: ^2.0.4 + minimalistic-assert: ^1.0.1 + minimalistic-crypto-utils: ^1.0.1 + checksum: 27b14a52f68bbbc0720da259f712cb73e953f6d2047958cd02fb0d0ade2e83849dc39fb4af630889c67df8817e24237428cf59c4f4c07700f755b401149a7375 languageName: node linkType: hard -"core-js-pure@npm:^3.0.1": - version: 3.26.0 - resolution: "core-js-pure@npm:3.26.0" - checksum: bbf5fa65cf3368a25f9d9cc525863acc8082fa3797efc8dc514f85d7f4aa870f4999b68863f3c7b96ed0b062add261a448758e6d337626c2535ad89ee8481a92 +"emoji-regex@npm:^7.0.1": + version: 7.0.3 + resolution: "emoji-regex@npm:7.0.3" + checksum: 9159b2228b1511f2870ac5920f394c7e041715429a68459ebe531601555f11ea782a8e1718f969df2711d38c66268174407cbca57ce36485544f695c2dfdc96e languageName: node linkType: hard -"core-js@npm:^1.0.0": - version: 1.2.7 - resolution: "core-js@npm:1.2.7" - checksum: 0b76371bfa98708351cde580f9287e2360d2209920e738ae950ae74ad08639a2e063541020bf666c28778956fc356ed9fe56d962129c88a87a6a4a0612526c75 +"emoji-regex@npm:^8.0.0": + version: 8.0.0 + resolution: "emoji-regex@npm:8.0.0" + checksum: d4c5c39d5a9868b5fa152f00cada8a936868fd3367f33f71be515ecee4c803132d11b31a6222b2571b1e5f7e13890156a94880345594d0ce7e3c9895f560f192 languageName: node linkType: hard -"core-js@npm:^2.4.0, core-js@npm:^2.5.0": - version: 2.6.12 - resolution: "core-js@npm:2.6.12" - checksum: 44fa9934a85f8c78d61e0c8b7b22436330471ffe59ec5076fe7f324d6e8cf7f824b14b1c81ca73608b13bdb0fef035bd820989bf059767ad6fa13123bb8bd016 +"encode-utf8@npm:^1.0.2": + version: 1.0.3 + resolution: "encode-utf8@npm:1.0.3" + checksum: 550224bf2a104b1d355458c8a82e9b4ea07f9fc78387bc3a49c151b940ad26473de8dc9e121eefc4e84561cb0b46de1e4cd2bc766f72ee145e9ea9541482817f languageName: node linkType: hard -"core-util-is@npm:1.0.2": +"encodeurl@npm:~1.0.2": version: 1.0.2 - resolution: "core-util-is@npm:1.0.2" - checksum: 7a4c925b497a2c91421e25bf76d6d8190f0b2359a9200dbeed136e63b2931d6294d3b1893eda378883ed363cd950f44a12a401384c609839ea616befb7927dab + resolution: "encodeurl@npm:1.0.2" + checksum: e50e3d508cdd9c4565ba72d2012e65038e5d71bdc9198cb125beb6237b5b1ade6c0d343998da9e170fb2eae52c1bed37d4d6d98a46ea423a0cddbed5ac3f780c languageName: node linkType: hard -"core-util-is@npm:~1.0.0": - version: 1.0.3 - resolution: "core-util-is@npm:1.0.3" - checksum: 9de8597363a8e9b9952491ebe18167e3b36e7707569eed0ebf14f8bba773611376466ae34575bca8cfe3c767890c859c74056084738f09d4e4a6f902b2ad7d99 +"encoding@npm:^0.1.12, encoding@npm:^0.1.13": + version: 0.1.13 + resolution: "encoding@npm:0.1.13" + dependencies: + iconv-lite: ^0.6.2 + checksum: bb98632f8ffa823996e508ce6a58ffcf5856330fde839ae42c9e1f436cc3b5cc651d4aeae72222916545428e54fd0f6aa8862fd8d25bdbcc4589f1e3f3715e7f languageName: node linkType: hard -"cors@npm:^2.8.1": - version: 2.8.5 - resolution: "cors@npm:2.8.5" +"end-of-stream@npm:^1.0.0, end-of-stream@npm:^1.1.0, end-of-stream@npm:^1.4.1": + version: 1.4.4 + resolution: "end-of-stream@npm:1.4.4" dependencies: - object-assign: ^4 - vary: ^1 - checksum: ced838404ccd184f61ab4fdc5847035b681c90db7ac17e428f3d81d69e2989d2b680cc254da0e2554f5ed4f8a341820a1ce3d1c16b499f6e2f47a1b9b07b5006 + once: ^1.4.0 + checksum: 530a5a5a1e517e962854a31693dbb5c0b2fc40b46dad2a56a2deec656ca040631124f4795823acc68238147805f8b021abbe221f4afed5ef3c8e8efc2024908b languageName: node linkType: hard -"cosmiconfig@npm:7.0.1": - version: 7.0.1 - resolution: "cosmiconfig@npm:7.0.1" +"enquirer@npm:2.3.6, enquirer@npm:^2.3.0, enquirer@npm:^2.3.4, enquirer@npm:^2.3.6": + version: 2.3.6 + resolution: "enquirer@npm:2.3.6" dependencies: - "@types/parse-json": ^4.0.0 - import-fresh: ^3.2.1 - parse-json: ^5.0.0 - path-type: ^4.0.0 - yaml: ^1.10.0 - checksum: 4be63e7117955fd88333d7460e4c466a90f556df6ef34efd59034d2463484e339666c41f02b523d574a797ec61f4a91918c5b89a316db2ea2f834e0d2d09465b + ansi-colors: ^4.1.1 + checksum: 1c0911e14a6f8d26721c91e01db06092a5f7675159f0261d69c403396a385afd13dd76825e7678f66daffa930cfaa8d45f506fb35f818a2788463d022af1b884 languageName: node linkType: hard -"cosmiconfig@npm:^5.0.7": - version: 5.2.1 - resolution: "cosmiconfig@npm:5.2.1" - dependencies: - import-fresh: ^2.0.0 - is-directory: ^0.3.1 - js-yaml: ^3.13.1 - parse-json: ^4.0.0 - checksum: 8b6f1d3c8a5ffdf663a952f17af0761adf210b7a5933d0fe8988f3ca3a1f0e1e5cbbb74d5b419c15933dd2fdcaec31dbc5cc85cb8259a822342b93b529eff89c - languageName: node - linkType: hard - -"crc-32@npm:^1.2.0": - version: 1.2.2 - resolution: "crc-32@npm:1.2.2" - bin: - crc32: bin/crc32.njs - checksum: ad2d0ad0cbd465b75dcaeeff0600f8195b686816ab5f3ba4c6e052a07f728c3e70df2e3ca9fd3d4484dc4ba70586e161ca5a2334ec8bf5a41bf022a6103ff243 - languageName: node - linkType: hard - -"create-ecdh@npm:^4.0.0": - version: 4.0.4 - resolution: "create-ecdh@npm:4.0.4" - dependencies: - bn.js: ^4.1.0 - elliptic: ^6.5.3 - checksum: 0dd7fca9711d09e152375b79acf1e3f306d1a25ba87b8ff14c2fd8e68b83aafe0a7dd6c4e540c9ffbdd227a5fa1ad9b81eca1f233c38bb47770597ba247e614b - languageName: node - linkType: hard - -"create-hash@npm:^1.1.0, create-hash@npm:^1.1.2, create-hash@npm:^1.2.0": - version: 1.2.0 - resolution: "create-hash@npm:1.2.0" - dependencies: - cipher-base: ^1.0.1 - inherits: ^2.0.1 - md5.js: ^1.3.4 - ripemd160: ^2.0.1 - sha.js: ^2.4.0 - checksum: 02a6ae3bb9cd4afee3fabd846c1d8426a0e6b495560a977ba46120c473cb283be6aa1cace76b5f927cf4e499c6146fb798253e48e83d522feba807d6b722eaa9 - languageName: node - linkType: hard - -"create-hmac@npm:^1.1.0, create-hmac@npm:^1.1.4, create-hmac@npm:^1.1.7": - version: 1.1.7 - resolution: "create-hmac@npm:1.1.7" - dependencies: - cipher-base: ^1.0.3 - create-hash: ^1.1.0 - inherits: ^2.0.1 - ripemd160: ^2.0.0 - safe-buffer: ^5.0.1 - sha.js: ^2.4.8 - checksum: ba12bb2257b585a0396108c72830e85f882ab659c3320c83584b1037f8ab72415095167ced80dc4ce8e446a8ecc4b2acf36d87befe0707d73b26cf9dc77440ed - languageName: node - linkType: hard - -"create-require@npm:^1.1.0": - version: 1.1.1 - resolution: "create-require@npm:1.1.1" - checksum: a9a1503d4390d8b59ad86f4607de7870b39cad43d929813599a23714831e81c520bddf61bcdd1f8e30f05fd3a2b71ae8538e946eb2786dc65c2bbc520f692eff - languageName: node - linkType: hard - -"cross-fetch@npm:^2.1.0, cross-fetch@npm:^2.1.1": - version: 2.2.6 - resolution: "cross-fetch@npm:2.2.6" - dependencies: - node-fetch: ^2.6.7 - whatwg-fetch: ^2.0.4 - checksum: df9c6728b314ff96022dca468a3d2a05b4546cd318d82a7e1f1445e7160472d39029bccbe5f20d319b8ba3793930592b0b956244aef6a87a133fbcfed85fc8ca - languageName: node - linkType: hard - -"cross-fetch@npm:^3.1.4": - version: 3.1.5 - resolution: "cross-fetch@npm:3.1.5" - dependencies: - node-fetch: 2.6.7 - checksum: f6b8c6ee3ef993ace6277fd789c71b6acf1b504fd5f5c7128df4ef2f125a429e29cd62dc8c127523f04a5f2fa4771ed80e3f3d9695617f441425045f505cf3bb - languageName: node - linkType: hard - -"cross-spawn@npm:7.0.3, cross-spawn@npm:^7.0.2, cross-spawn@npm:^7.0.3": - version: 7.0.3 - resolution: "cross-spawn@npm:7.0.3" - dependencies: - path-key: ^3.1.0 - shebang-command: ^2.0.0 - which: ^2.0.1 - checksum: 671cc7c7288c3a8406f3c69a3ae2fc85555c04169e9d611def9a675635472614f1c0ed0ef80955d5b6d4e724f6ced67f0ad1bb006c2ea643488fcfef994d7f52 - languageName: node - linkType: hard - -"cross-spawn@npm:^6.0.0, cross-spawn@npm:^6.0.5": - version: 6.0.5 - resolution: "cross-spawn@npm:6.0.5" - dependencies: - nice-try: ^1.0.4 - path-key: ^2.0.1 - semver: ^5.5.0 - shebang-command: ^1.2.0 - which: ^1.2.9 - checksum: f893bb0d96cd3d5751d04e67145bdddf25f99449531a72e82dcbbd42796bbc8268c1076c6b3ea51d4d455839902804b94bc45dfb37ecbb32ea8e54a6741c3ab9 - languageName: node - linkType: hard - -"crypt@npm:>= 0.0.1": - version: 0.0.2 - resolution: "crypt@npm:0.0.2" - checksum: baf4c7bbe05df656ec230018af8cf7dbe8c14b36b98726939cef008d473f6fe7a4fad906cfea4062c93af516f1550a3f43ceb4d6615329612c6511378ed9fe34 - languageName: node - linkType: hard - -"crypto-browserify@npm:3.12.0": - version: 3.12.0 - resolution: "crypto-browserify@npm:3.12.0" - dependencies: - browserify-cipher: ^1.0.0 - browserify-sign: ^4.0.0 - create-ecdh: ^4.0.0 - create-hash: ^1.1.0 - create-hmac: ^1.1.0 - diffie-hellman: ^5.0.0 - inherits: ^2.0.1 - pbkdf2: ^3.0.3 - public-encrypt: ^4.0.0 - randombytes: ^2.0.0 - randomfill: ^1.0.3 - checksum: c1609af82605474262f3eaa07daa0b2140026bd264ab316d4bf1170272570dbe02f0c49e29407fe0d3634f96c507c27a19a6765fb856fed854a625f9d15618e2 - languageName: node - linkType: hard - -"crypto-js@npm:4.1.1": - version: 4.1.1 - resolution: "crypto-js@npm:4.1.1" - checksum: b3747c12ee3a7632fab3b3e171ea50f78b182545f0714f6d3e7e2858385f0f4101a15f2517e033802ce9d12ba50a391575ff4638c9de3dd9b2c4bc47768d5425 - languageName: node - linkType: hard - -"crypto-js@npm:4.2.0": - version: 4.2.0 - resolution: "crypto-js@npm:4.2.0" - checksum: f051666dbc077c8324777f44fbd3aaea2986f198fe85092535130d17026c7c2ccf2d23ee5b29b36f7a4a07312db2fae23c9094b644cc35f7858b1b4fcaf27774 - languageName: node - linkType: hard - -"d@npm:1, d@npm:^1.0.1": - version: 1.0.1 - resolution: "d@npm:1.0.1" - dependencies: - es5-ext: ^0.10.50 - type: ^1.0.1 - checksum: 49ca0639c7b822db670de93d4fbce44b4aa072cd848c76292c9978a8cd0fff1028763020ff4b0f147bd77bfe29b4c7f82e0f71ade76b2a06100543cdfd948d19 - languageName: node - linkType: hard - -"dashdash@npm:^1.12.0": - version: 1.14.1 - resolution: "dashdash@npm:1.14.1" - dependencies: - assert-plus: ^1.0.0 - checksum: 3634c249570f7f34e3d34f866c93f866c5b417f0dd616275decae08147dcdf8fccfaa5947380ccfb0473998ea3a8057c0b4cd90c875740ee685d0624b2983598 - languageName: node - linkType: hard - -"death@npm:^1.1.0": - version: 1.1.0 - resolution: "death@npm:1.1.0" - checksum: 8010ba9a320752f9580eb474985ed214572c0595cf83e92859e3c5a014a01fc8e8f2f2908b80b5f8bca9cb3f94adb546cf55810df6b80e282452e355cdce5aaa - languageName: node - linkType: hard - -"debug@npm:2.6.9, debug@npm:^2.2.0, debug@npm:^2.3.3, debug@npm:^2.6.8, debug@npm:^2.6.9": - version: 2.6.9 - resolution: "debug@npm:2.6.9" - dependencies: - ms: 2.0.0 - checksum: d2f51589ca66df60bf36e1fa6e4386b318c3f1e06772280eea5b1ae9fd3d05e9c2b7fd8a7d862457d00853c75b00451aa2d7459b924629ee385287a650f58fe6 - languageName: node - linkType: hard - -"debug@npm:3.2.6": - version: 3.2.6 - resolution: "debug@npm:3.2.6" - dependencies: - ms: ^2.1.1 - checksum: 07bc8b3a13ef3cfa6c06baf7871dfb174c291e5f85dbf566f086620c16b9c1a0e93bb8f1935ebbd07a683249e7e30286f2966e2ef461e8fd17b1b60732062d6b - languageName: node - linkType: hard - -"debug@npm:4, debug@npm:4.3.3, debug@npm:^4.0.1, debug@npm:^4.1.0, debug@npm:^4.1.1, debug@npm:^4.3.1, debug@npm:^4.3.2": - version: 4.3.3 - resolution: "debug@npm:4.3.3" - dependencies: - ms: 2.1.2 - peerDependenciesMeta: - supports-color: - optional: true - checksum: 14472d56fe4a94dbcfaa6dbed2dd3849f1d72ba78104a1a328047bb564643ca49df0224c3a17fa63533fd11dd3d4c8636cd861191232a2c6735af00cc2d4de16 - languageName: node - linkType: hard - -"debug@npm:4.3.4, debug@npm:^4.3.3, debug@npm:^4.3.4": - version: 4.3.4 - resolution: "debug@npm:4.3.4" - dependencies: - ms: 2.1.2 - peerDependenciesMeta: - supports-color: - optional: true - checksum: 3dbad3f94ea64f34431a9cbf0bafb61853eda57bff2880036153438f50fb5a84f27683ba0d8e5426bf41a8c6ff03879488120cf5b3a761e77953169c0600a708 - languageName: node - linkType: hard - -"debug@npm:^3.1.0, debug@npm:^3.2.6, debug@npm:^3.2.7": - version: 3.2.7 - resolution: "debug@npm:3.2.7" - dependencies: - ms: ^2.1.1 - checksum: b3d8c5940799914d30314b7c3304a43305fd0715581a919dacb8b3176d024a782062368405b47491516d2091d6462d4d11f2f4974a405048094f8bfebfa3071c - languageName: node - linkType: hard - -"decamelize@npm:^1.1.1, decamelize@npm:^1.2.0": - version: 1.2.0 - resolution: "decamelize@npm:1.2.0" - checksum: ad8c51a7e7e0720c70ec2eeb1163b66da03e7616d7b98c9ef43cce2416395e84c1e9548dd94f5f6ffecfee9f8b94251fc57121a8b021f2ff2469b2bae247b8aa - languageName: node - linkType: hard - -"decamelize@npm:^4.0.0": - version: 4.0.0 - resolution: "decamelize@npm:4.0.0" - checksum: b7d09b82652c39eead4d6678bb578e3bebd848add894b76d0f6b395bc45b2d692fb88d977e7cfb93c4ed6c119b05a1347cef261174916c2e75c0a8ca57da1809 - languageName: node - linkType: hard - -"decode-uri-component@npm:^0.2.0": - version: 0.2.0 - resolution: "decode-uri-component@npm:0.2.0" - checksum: f3749344ab9305ffcfe4bfe300e2dbb61fc6359e2b736812100a3b1b6db0a5668cba31a05e4b45d4d63dbf1a18dfa354cd3ca5bb3ededddabb8cd293f4404f94 - languageName: node - linkType: hard - -"decompress-response@npm:^3.3.0": - version: 3.3.0 - resolution: "decompress-response@npm:3.3.0" - dependencies: - mimic-response: ^1.0.0 - checksum: 952552ac3bd7de2fc18015086b09468645c9638d98a551305e485230ada278c039c91116e946d07894b39ee53c0f0d5b6473f25a224029344354513b412d7380 - languageName: node - linkType: hard - -"decompress-response@npm:^6.0.0": - version: 6.0.0 - resolution: "decompress-response@npm:6.0.0" - dependencies: - mimic-response: ^3.1.0 - checksum: d377cf47e02d805e283866c3f50d3d21578b779731e8c5072d6ce8c13cc31493db1c2f6784da9d1d5250822120cefa44f1deab112d5981015f2e17444b763812 - languageName: node - linkType: hard - -"deep-eql@npm:^3.0.1": - version: 3.0.1 - resolution: "deep-eql@npm:3.0.1" - dependencies: - type-detect: ^4.0.0 - checksum: 4f4c9fb79eb994fb6e81d4aa8b063adc40c00f831588aa65e20857d5d52f15fb23034a6576ecf886f7ff6222d5ae42e71e9b7d57113e0715b1df7ea1e812b125 - languageName: node - linkType: hard - -"deep-equal@npm:~1.1.1": - version: 1.1.1 - resolution: "deep-equal@npm:1.1.1" - dependencies: - is-arguments: ^1.0.4 - is-date-object: ^1.0.1 - is-regex: ^1.0.4 - object-is: ^1.0.1 - object-keys: ^1.1.1 - regexp.prototype.flags: ^1.2.0 - checksum: f92686f2c5bcdf714a75a5fa7a9e47cb374a8ec9307e717b8d1ce61f56a75aaebf5619c2a12b8087a705b5a2f60d0292c35f8b58cb1f72e3268a3a15cab9f78d - languageName: node - linkType: hard - -"deep-extend@npm:^0.6.0, deep-extend@npm:~0.6.0": - version: 0.6.0 - resolution: "deep-extend@npm:0.6.0" - checksum: 7be7e5a8d468d6b10e6a67c3de828f55001b6eb515d014f7aeb9066ce36bd5717161eb47d6a0f7bed8a9083935b465bc163ee2581c8b128d29bf61092fdf57a7 - languageName: node - linkType: hard - -"deep-is@npm:^0.1.3, deep-is@npm:~0.1.3": - version: 0.1.4 - resolution: "deep-is@npm:0.1.4" - checksum: edb65dd0d7d1b9c40b2f50219aef30e116cedd6fc79290e740972c132c09106d2e80aa0bc8826673dd5a00222d4179c84b36a790eef63a4c4bca75a37ef90804 - languageName: node - linkType: hard - -"defaults@npm:^1.0.3": - version: 1.0.3 - resolution: "defaults@npm:1.0.3" - dependencies: - clone: ^1.0.2 - checksum: 96e2112da6553d376afd5265ea7cbdb2a3b45535965d71ab8bb1da10c8126d168fdd5268799625324b368356d21ba2a7b3d4ec50961f11a47b7feb9de3d4413e - languageName: node - linkType: hard - -"defer-to-connect@npm:^1.0.1": - version: 1.1.3 - resolution: "defer-to-connect@npm:1.1.3" - checksum: 9491b301dcfa04956f989481ba7a43c2231044206269eb4ab64a52d6639ee15b1252262a789eb4239fb46ab63e44d4e408641bae8e0793d640aee55398cb3930 - languageName: node - linkType: hard - -"defer-to-connect@npm:^2.0.0, defer-to-connect@npm:^2.0.1": - version: 2.0.1 - resolution: "defer-to-connect@npm:2.0.1" - checksum: 8a9b50d2f25446c0bfefb55a48e90afd58f85b21bcf78e9207cd7b804354f6409032a1705c2491686e202e64fc05f147aa5aa45f9aa82627563f045937f5791b - languageName: node - linkType: hard - -"deferred-leveldown@npm:~1.2.1": - version: 1.2.2 - resolution: "deferred-leveldown@npm:1.2.2" - dependencies: - abstract-leveldown: ~2.6.0 - checksum: ad3a26d20dc80c702c85c4795cbb52ef25d8e500728c98098b468c499ca745051e6cc03bd12be97ff38c43466a7895879db76ffb761a75b0f009829d990a0ea9 - languageName: node - linkType: hard - -"deferred-leveldown@npm:~4.0.0": - version: 4.0.2 - resolution: "deferred-leveldown@npm:4.0.2" - dependencies: - abstract-leveldown: ~5.0.0 - inherits: ^2.0.3 - checksum: 6b3649bbb7a2617e08eecdddb516d0bde215bd376a37089df203ad78627f59c424c785afbcbfd3e53488d4f9e5d27d9d126d5645b7da53e8760cc34df2d2f13e - languageName: node - linkType: hard - -"deferred-leveldown@npm:~5.3.0": - version: 5.3.0 - resolution: "deferred-leveldown@npm:5.3.0" - dependencies: - abstract-leveldown: ~6.2.1 - inherits: ^2.0.3 - checksum: 5631e153528bb9de1aa60d59a5065d1a519374c5e4c1d486f2190dba4008dcf5c2ee8dd7f2f81396fc4d5a6bb6e7d0055e3dfe68afe00da02adaa3bf329addf7 - languageName: node - linkType: hard - -"define-data-property@npm:^1.0.1": - version: 1.1.0 - resolution: "define-data-property@npm:1.1.0" - dependencies: - get-intrinsic: ^1.2.1 - gopd: ^1.0.1 - has-property-descriptors: ^1.0.0 - checksum: 7ad4ee84cca8ad427a4831f5693526804b62ce9dfd4efac77214e95a4382aed930072251d4075dc8dc9fc949a353ed51f19f5285a84a788ba9216cc51472a093 - languageName: node - linkType: hard - -"define-properties@npm:^1.1.2, define-properties@npm:^1.1.4": - version: 1.1.4 - resolution: "define-properties@npm:1.1.4" - dependencies: - has-property-descriptors: ^1.0.0 - object-keys: ^1.1.1 - checksum: ce0aef3f9eb193562b5cfb79b2d2c86b6a109dfc9fdcb5f45d680631a1a908c06824ddcdb72b7573b54e26ace07f0a23420aaba0d5c627b34d2c1de8ef527e2b - languageName: node - linkType: hard - -"define-properties@npm:^1.1.3": - version: 1.1.3 - resolution: "define-properties@npm:1.1.3" - dependencies: - object-keys: ^1.0.12 - checksum: da80dba55d0cd76a5a7ab71ef6ea0ebcb7b941f803793e4e0257b384cb772038faa0c31659d244e82c4342edef841c1a1212580006a05a5068ee48223d787317 - languageName: node - linkType: hard - -"define-properties@npm:^1.2.0": - version: 1.2.1 - resolution: "define-properties@npm:1.2.1" - dependencies: - define-data-property: ^1.0.1 - has-property-descriptors: ^1.0.0 - object-keys: ^1.1.1 - checksum: b4ccd00597dd46cb2d4a379398f5b19fca84a16f3374e2249201992f36b30f6835949a9429669ee6b41b6e837205a163eadd745e472069e70dfc10f03e5fcc12 - languageName: node - linkType: hard - -"define-property@npm:^0.2.5": - version: 0.2.5 - resolution: "define-property@npm:0.2.5" - dependencies: - is-descriptor: ^0.1.0 - checksum: 85af107072b04973b13f9e4128ab74ddfda48ec7ad2e54b193c0ffb57067c4ce5b7786a7b4ae1f24bd03e87c5d18766b094571810b314d7540f86d4354dbd394 - languageName: node - linkType: hard - -"define-property@npm:^1.0.0": - version: 1.0.0 - resolution: "define-property@npm:1.0.0" - dependencies: - is-descriptor: ^1.0.0 - checksum: 5fbed11dace44dd22914035ba9ae83ad06008532ca814d7936a53a09e897838acdad5b108dd0688cc8d2a7cf0681acbe00ee4136cf36743f680d10517379350a - languageName: node - linkType: hard - -"define-property@npm:^2.0.2": - version: 2.0.2 - resolution: "define-property@npm:2.0.2" - dependencies: - is-descriptor: ^1.0.2 - isobject: ^3.0.1 - checksum: 3217ed53fc9eed06ba8da6f4d33e28c68a82e2f2a8ab4d562c4920d8169a166fe7271453675e6c69301466f36a65d7f47edf0cf7f474b9aa52a5ead9c1b13c99 - languageName: node - linkType: hard - -"defined@npm:~1.0.0": - version: 1.0.1 - resolution: "defined@npm:1.0.1" - checksum: b1a852300bdb57f297289b55eafdd0c517afaa3ec8190e78fce91b9d8d0c0369d4505ecbdacfd3d98372e664f4a267d9bd793938d4a8c76209c9d9516fbe2101 - languageName: node - linkType: hard - -"delay@npm:^5.0.0": - version: 5.0.0 - resolution: "delay@npm:5.0.0" - checksum: 62f151151ecfde0d9afbb8a6be37a6d103c4cb24f35a20ef3fe56f920b0d0d0bb02bc9c0a3084d0179ef669ca332b91155f2ee4d9854622cd2cdba5fc95285f9 - languageName: node - linkType: hard - -"delayed-stream@npm:~1.0.0": - version: 1.0.0 - resolution: "delayed-stream@npm:1.0.0" - checksum: 46fe6e83e2cb1d85ba50bd52803c68be9bd953282fa7096f51fc29edd5d67ff84ff753c51966061e5ba7cb5e47ef6d36a91924eddb7f3f3483b1c560f77a0020 - languageName: node - linkType: hard - -"delegates@npm:^1.0.0": - version: 1.0.0 - resolution: "delegates@npm:1.0.0" - checksum: a51744d9b53c164ba9c0492471a1a2ffa0b6727451bdc89e31627fdf4adda9d51277cfcbfb20f0a6f08ccb3c436f341df3e92631a3440226d93a8971724771fd - languageName: node - linkType: hard - -"depd@npm:2.0.0": - version: 2.0.0 - resolution: "depd@npm:2.0.0" - checksum: abbe19c768c97ee2eed6282d8ce3031126662252c58d711f646921c9623f9052e3e1906443066beec1095832f534e57c523b7333f8e7e0d93051ab6baef5ab3a - languageName: node - linkType: hard - -"depd@npm:^1.1.2": - version: 1.1.2 - resolution: "depd@npm:1.1.2" - checksum: 6b406620d269619852885ce15965272b829df6f409724415e0002c8632ab6a8c0a08ec1f0bd2add05dc7bd7507606f7e2cc034fa24224ab829580040b835ecd9 - languageName: node - linkType: hard - -"des.js@npm:^1.0.0": - version: 1.0.1 - resolution: "des.js@npm:1.0.1" - dependencies: - inherits: ^2.0.1 - minimalistic-assert: ^1.0.0 - checksum: 1ec2eedd7ed6bd61dd5e0519fd4c96124e93bb22de8a9d211b02d63e5dd152824853d919bb2090f965cc0e3eb9c515950a9836b332020d810f9c71feb0fd7df4 - languageName: node - linkType: hard - -"destroy@npm:1.2.0": - version: 1.2.0 - resolution: "destroy@npm:1.2.0" - checksum: 0acb300b7478a08b92d810ab229d5afe0d2f4399272045ab22affa0d99dbaf12637659411530a6fcd597a9bdac718fc94373a61a95b4651bbc7b83684a565e38 - languageName: node - linkType: hard - -"detect-indent@npm:^4.0.0": - version: 4.0.0 - resolution: "detect-indent@npm:4.0.0" - dependencies: - repeating: ^2.0.0 - checksum: 328f273915c1610899bc7d4784ce874413d0a698346364cd3ee5d79afba1c5cf4dbc97b85a801e20f4d903c0598bd5096af32b800dfb8696b81464ccb3dfda2c - languageName: node - linkType: hard - -"detect-libc@npm:^2.0.0": - version: 2.0.2 - resolution: "detect-libc@npm:2.0.2" - checksum: 2b2cd3649b83d576f4be7cc37eb3b1815c79969c8b1a03a40a4d55d83bc74d010753485753448eacb98784abf22f7dbd3911fd3b60e29fda28fed2d1a997944d - languageName: node - linkType: hard - -"detect-port@npm:^1.3.0": - version: 1.5.1 - resolution: "detect-port@npm:1.5.1" - dependencies: - address: ^1.0.1 - debug: 4 - bin: - detect: bin/detect-port.js - detect-port: bin/detect-port.js - checksum: b48da9340481742547263d5d985e65d078592557863402ecf538511735e83575867e94f91fe74405ea19b61351feb99efccae7e55de9a151d5654e3417cea05b - languageName: node - linkType: hard - -"diff@npm:3.5.0": - version: 3.5.0 - resolution: "diff@npm:3.5.0" - checksum: 00842950a6551e26ce495bdbce11047e31667deea546527902661f25cc2e73358967ebc78cf86b1a9736ec3e14286433225f9970678155753a6291c3bca5227b - languageName: node - linkType: hard - -"diff@npm:5.0.0": - version: 5.0.0 - resolution: "diff@npm:5.0.0" - checksum: f19fe29284b633afdb2725c2a8bb7d25761ea54d321d8e67987ac851c5294be4afeab532bd84531e02583a3fe7f4014aa314a3eda84f5590e7a9e6b371ef3b46 - languageName: node - linkType: hard - -"diff@npm:^4.0.1": - version: 4.0.2 - resolution: "diff@npm:4.0.2" - checksum: f2c09b0ce4e6b301c221addd83bf3f454c0bc00caa3dd837cf6c127d6edf7223aa2bbe3b688feea110b7f262adbfc845b757c44c8a9f8c0c5b15d8fa9ce9d20d - languageName: node - linkType: hard - -"diffie-hellman@npm:^5.0.0": - version: 5.0.3 - resolution: "diffie-hellman@npm:5.0.3" - dependencies: - bn.js: ^4.1.0 - miller-rabin: ^4.0.0 - randombytes: ^2.0.0 - checksum: 0e620f322170c41076e70181dd1c24e23b08b47dbb92a22a644f3b89b6d3834b0f8ee19e37916164e5eb1ee26d2aa836d6129f92723995267250a0b541811065 - languageName: node - linkType: hard - -"dir-glob@npm:^3.0.1": - version: 3.0.1 - resolution: "dir-glob@npm:3.0.1" - dependencies: - path-type: ^4.0.0 - checksum: fa05e18324510d7283f55862f3161c6759a3f2f8dbce491a2fc14c8324c498286c54282c1f0e933cb930da8419b30679389499b919122952a4f8592362ef4615 - languageName: node - linkType: hard - -"disklet@npm:^0.4.5": - version: 0.4.6 - resolution: "disklet@npm:0.4.6" - dependencies: - rfc4648: ^1.3.0 - checksum: 2fc9e781b05edb1f9bce10a6aa9c00e90fb291f66c84837dcedd7b49fe7fd9449d5ee53e8009edcbf54c68dbd9119c65539eab2a8b4b0178a4c53252deb4056f - languageName: node - linkType: hard - -"disklet@npm:^0.5.0": - version: 0.5.2 - resolution: "disklet@npm:0.5.2" - dependencies: - rfc4648: ^1.3.0 - checksum: 87c78fd781c6ecbcee1f095327857b7c74b8b8dcc305ebb97312367523b50a2bf6c3499615c5345bfc15210e384816d6a4cfd109081c3059a48479d3acf01012 - languageName: node - linkType: hard - -"dns-over-http-resolver@npm:^1.2.3": - version: 1.2.3 - resolution: "dns-over-http-resolver@npm:1.2.3" - dependencies: - debug: ^4.3.1 - native-fetch: ^3.0.0 - receptacle: ^1.3.2 - checksum: 3cc1a1d77fc43e7a8a12453da987b80860ac96dc1031386c5eb1a39154775a87cfa1d50c0eaa5ea5e397e898791654608f6e2acf03f750f4098ab8822bb7d928 - languageName: node - linkType: hard - -"docker-compose@npm:0.23.19": - version: 0.23.19 - resolution: "docker-compose@npm:0.23.19" - dependencies: - yaml: ^1.10.2 - checksum: 1704825954ec8645e4b099cc2641531955eef5a8a9729c885fab7067ae4d7935c663252e51b49878397e51cd5a3efcf2f13c8460e252aa39d14a0722c0bacfe5 - languageName: node - linkType: hard - -"docker-modem@npm:^1.0.8": - version: 1.0.9 - resolution: "docker-modem@npm:1.0.9" - dependencies: - JSONStream: 1.3.2 - debug: ^3.2.6 - readable-stream: ~1.0.26-4 - split-ca: ^1.0.0 - checksum: b34829f5abecf28332f1870c88bdf795750520264e9fdc8e9041058f18b1846543061ee32fb21ff14e9da6b5498af6b2cb4d96422d8c2dc02d9f622b01f34fe6 - languageName: node - linkType: hard - -"dockerode@npm:2.5.8": - version: 2.5.8 - resolution: "dockerode@npm:2.5.8" - dependencies: - concat-stream: ~1.6.2 - docker-modem: ^1.0.8 - tar-fs: ~1.16.3 - checksum: 01381da98f98a3236b735fb2bb2a66f521da39200a2a11b83777cee3b104b32966ba7dfeb93f3fa8ab85b5e639265842d66f576e7db9562b1049564c2af6ec84 - languageName: node - linkType: hard - -"doctrine@npm:^2.1.0": - version: 2.1.0 - resolution: "doctrine@npm:2.1.0" - dependencies: - esutils: ^2.0.2 - checksum: a45e277f7feaed309fe658ace1ff286c6e2002ac515af0aaf37145b8baa96e49899638c7cd47dccf84c3d32abfc113246625b3ac8f552d1046072adee13b0dc8 - languageName: node - linkType: hard - -"doctrine@npm:^3.0.0": - version: 3.0.0 - resolution: "doctrine@npm:3.0.0" - dependencies: - esutils: ^2.0.2 - checksum: fd7673ca77fe26cd5cba38d816bc72d641f500f1f9b25b83e8ce28827fe2da7ad583a8da26ab6af85f834138cf8dae9f69b0cd6ab925f52ddab1754db44d99ce - languageName: node - linkType: hard - -"dom-walk@npm:^0.1.0": - version: 0.1.2 - resolution: "dom-walk@npm:0.1.2" - checksum: 19eb0ce9c6de39d5e231530685248545d9cd2bd97b2cb3486e0bfc0f2a393a9addddfd5557463a932b52fdfcf68ad2a619020cd2c74a5fe46fbecaa8e80872f3 - languageName: node - linkType: hard - -"dotenv@npm:^10.0.0": - version: 10.0.0 - resolution: "dotenv@npm:10.0.0" - checksum: f412c5fe8c24fbe313d302d2500e247ba8a1946492db405a4de4d30dd0eb186a88a43f13c958c5a7de303938949c4231c56994f97d05c4bc1f22478d631b4005 - languageName: node - linkType: hard - -"dotignore@npm:~0.1.2": - version: 0.1.2 - resolution: "dotignore@npm:0.1.2" - dependencies: - minimatch: ^3.0.4 - bin: - ignored: bin/ignored - checksum: 06bab15e2a2400c6f823a0edbcd73661180f6245a4041a3fe3b9fde4b22ae74b896604df4520a877093f05c656bd080087376c9f605bccdea847664c59910f37 - languageName: node - linkType: hard - -"duplexer3@npm:^0.1.4": - version: 0.1.5 - resolution: "duplexer3@npm:0.1.5" - checksum: e677cb4c48f031ca728601d6a20bf6aed4c629d69ef9643cb89c67583d673c4ec9317cc6427501f38bd8c368d3a18f173987cc02bd99d8cf8fe3d94259a22a20 - languageName: node - linkType: hard - -"ecc-jsbn@npm:~0.1.1": - version: 0.1.2 - resolution: "ecc-jsbn@npm:0.1.2" - dependencies: - jsbn: ~0.1.0 - safer-buffer: ^2.1.0 - checksum: 22fef4b6203e5f31d425f5b711eb389e4c6c2723402e389af394f8411b76a488fa414d309d866e2b577ce3e8462d344205545c88a8143cc21752a5172818888a - languageName: node - linkType: hard - -"ee-first@npm:1.1.1": - version: 1.1.1 - resolution: "ee-first@npm:1.1.1" - checksum: 1b4cac778d64ce3b582a7e26b218afe07e207a0f9bfe13cc7395a6d307849cfe361e65033c3251e00c27dd060cab43014c2d6b2647676135e18b77d2d05b3f4f - languageName: node - linkType: hard - -"eip55@npm:^2.1.1": - version: 2.1.1 - resolution: "eip55@npm:2.1.1" - dependencies: - keccak: ^3.0.3 - checksum: 512d319e4f91ab0c33b514f371206956521dcdcdd23e8eb4d6f9c21e3be9f72287c0b82feb854d3a1eec91805804d13c31e7a1a7dafd37f69eb9994a9c6c8f32 - languageName: node - linkType: hard - -"ejs@npm:3.1.6": - version: 3.1.6 - resolution: "ejs@npm:3.1.6" - dependencies: - jake: ^10.6.1 - bin: - ejs: ./bin/cli.js - checksum: 81a9cdea0b4ded3b5a4b212b7c17e20bb07468f08394e2d519708d367957a70aef3d282a6d5d38bf6ad313ba25802b9193d4227f29b084d2ee0f28d115141d48 - languageName: node - linkType: hard - -"ejs@npm:^3.1.8": - version: 3.1.9 - resolution: "ejs@npm:3.1.9" - dependencies: - jake: ^10.8.5 - bin: - ejs: bin/cli.js - checksum: af6f10eb815885ff8a8cfacc42c6b6cf87daf97a4884f87a30e0c3271fedd85d76a3a297d9c33a70e735b97ee632887f85e32854b9cdd3a2d97edf931519a35f - languageName: node - linkType: hard - -"electron-fetch@npm:^1.7.2": - version: 1.9.1 - resolution: "electron-fetch@npm:1.9.1" - dependencies: - encoding: ^0.1.13 - checksum: 33b5d363b9a234288e847237ef34536bd415f31cba3b1c69b2ae4679a2bae66fb7ded2b576b90a0b7cd240e3df71cf16f2b961d4ab82864df02b6b53cf49f05c - languageName: node - linkType: hard - -"electron-to-chromium@npm:^1.3.47": - version: 1.4.284 - resolution: "electron-to-chromium@npm:1.4.284" - checksum: be496e9dca6509dbdbb54dc32146fc99f8eb716d28a7ee8ccd3eba0066561df36fc51418d8bd7cf5a5891810bf56c0def3418e74248f51ea4a843d423603d10a - languageName: node - linkType: hard - -"elliptic@npm:6.5.4, elliptic@npm:^6.4.0, elliptic@npm:^6.5.2, elliptic@npm:^6.5.3": - version: 6.5.4 - resolution: "elliptic@npm:6.5.4" - dependencies: - bn.js: ^4.11.9 - brorand: ^1.1.0 - hash.js: ^1.0.0 - hmac-drbg: ^1.0.1 - inherits: ^2.0.4 - minimalistic-assert: ^1.0.1 - minimalistic-crypto-utils: ^1.0.1 - checksum: d56d21fd04e97869f7ffcc92e18903b9f67f2d4637a23c860492fbbff5a3155fd9ca0184ce0c865dd6eb2487d234ce9551335c021c376cd2d3b7cb749c7d10f4 - languageName: node - linkType: hard - -"emoji-regex@npm:^10.1.0": - version: 10.2.1 - resolution: "emoji-regex@npm:10.2.1" - checksum: 1aa2d16881c56531fdfc03d0b36f5c2b6221cc4097499a5665b88b711dc3fb4d5b8804f0ca6f00c56e5dcf89bac75f0487eee85da1da77df3a33accc6ecbe426 - languageName: node - linkType: hard - -"emoji-regex@npm:^7.0.1": - version: 7.0.3 - resolution: "emoji-regex@npm:7.0.3" - checksum: 9159b2228b1511f2870ac5920f394c7e041715429a68459ebe531601555f11ea782a8e1718f969df2711d38c66268174407cbca57ce36485544f695c2dfdc96e - languageName: node - linkType: hard - -"emoji-regex@npm:^8.0.0": - version: 8.0.0 - resolution: "emoji-regex@npm:8.0.0" - checksum: d4c5c39d5a9868b5fa152f00cada8a936868fd3367f33f71be515ecee4c803132d11b31a6222b2571b1e5f7e13890156a94880345594d0ce7e3c9895f560f192 - languageName: node - linkType: hard - -"encode-utf8@npm:^1.0.2": - version: 1.0.3 - resolution: "encode-utf8@npm:1.0.3" - checksum: 550224bf2a104b1d355458c8a82e9b4ea07f9fc78387bc3a49c151b940ad26473de8dc9e121eefc4e84561cb0b46de1e4cd2bc766f72ee145e9ea9541482817f - languageName: node - linkType: hard - -"encodeurl@npm:~1.0.2": - version: 1.0.2 - resolution: "encodeurl@npm:1.0.2" - checksum: e50e3d508cdd9c4565ba72d2012e65038e5d71bdc9198cb125beb6237b5b1ade6c0d343998da9e170fb2eae52c1bed37d4d6d98a46ea423a0cddbed5ac3f780c - languageName: node - linkType: hard - -"encoding-down@npm:5.0.4, encoding-down@npm:~5.0.0": - version: 5.0.4 - resolution: "encoding-down@npm:5.0.4" - dependencies: - abstract-leveldown: ^5.0.0 - inherits: ^2.0.3 - level-codec: ^9.0.0 - level-errors: ^2.0.0 - xtend: ^4.0.1 - checksum: b8d9d4b058622c11e33d8ec0fb6432194925e109ed8e44e93555406496e8b77b294c8c338dd5ed9ab8d7bc50250a48bb93f9af62ecee3ce8d82f4ef78b2ca880 - languageName: node - linkType: hard - -"encoding-down@npm:^6.3.0": - version: 6.3.0 - resolution: "encoding-down@npm:6.3.0" - dependencies: - abstract-leveldown: ^6.2.1 - inherits: ^2.0.3 - level-codec: ^9.0.0 - level-errors: ^2.0.0 - checksum: 74043e6d9061a470614ff61d708c849259ab32932a428fd5ddfb0878719804f56a52f59b31cccd95fddc2e636c0fd22dc3e02481fb98d5bf1bdbbbc44ca09bdc - languageName: node - linkType: hard - -"encoding@npm:^0.1.11, encoding@npm:^0.1.12, encoding@npm:^0.1.13": - version: 0.1.13 - resolution: "encoding@npm:0.1.13" - dependencies: - iconv-lite: ^0.6.2 - checksum: bb98632f8ffa823996e508ce6a58ffcf5856330fde839ae42c9e1f436cc3b5cc651d4aeae72222916545428e54fd0f6aa8862fd8d25bdbcc4589f1e3f3715e7f - languageName: node - linkType: hard - -"end-of-stream@npm:^1.0.0, end-of-stream@npm:^1.1.0, end-of-stream@npm:^1.4.1": - version: 1.4.4 - resolution: "end-of-stream@npm:1.4.4" - dependencies: - once: ^1.4.0 - checksum: 530a5a5a1e517e962854a31693dbb5c0b2fc40b46dad2a56a2deec656ca040631124f4795823acc68238147805f8b021abbe221f4afed5ef3c8e8efc2024908b - languageName: node - linkType: hard - -"enquirer@npm:2.3.6, enquirer@npm:^2.3.0, enquirer@npm:^2.3.4, enquirer@npm:^2.3.5, enquirer@npm:^2.3.6": - version: 2.3.6 - resolution: "enquirer@npm:2.3.6" - dependencies: - ansi-colors: ^4.1.1 - checksum: 1c0911e14a6f8d26721c91e01db06092a5f7675159f0261d69c403396a385afd13dd76825e7678f66daffa930cfaa8d45f506fb35f818a2788463d022af1b884 - languageName: node - linkType: hard - -"env-paths@npm:^2.2.0": - version: 2.2.1 - resolution: "env-paths@npm:2.2.1" - checksum: 65b5df55a8bab92229ab2b40dad3b387fad24613263d103a97f91c9fe43ceb21965cd3392b1ccb5d77088021e525c4e0481adb309625d0cb94ade1d1fb8dc17e - languageName: node - linkType: hard - -"err-code@npm:^2.0.2": - version: 2.0.3 - resolution: "err-code@npm:2.0.3" - checksum: 8b7b1be20d2de12d2255c0bc2ca638b7af5171142693299416e6a9339bd7d88fc8d7707d913d78e0993176005405a236b066b45666b27b797252c771156ace54 - languageName: node - linkType: hard - -"err-code@npm:^3.0.1": - version: 3.0.1 - resolution: "err-code@npm:3.0.1" - checksum: aede1f1d5ebe6d6b30b5e3175e3cc13e67de2e2e1ad99ce4917e957d7b59e8451ed10ee37dbc6493521920a47082c479b9097e5c39438d4aff4cc84438568a5a - languageName: node - linkType: hard - -"errno@npm:~0.1.1": - version: 0.1.8 - resolution: "errno@npm:0.1.8" - dependencies: - prr: ~1.0.1 - bin: - errno: cli.js - checksum: 1271f7b9fbb3bcbec76ffde932485d1e3561856d21d847ec613a9722ee924cdd4e523a62dc71a44174d91e898fe21fdc8d5b50823f4b5e0ce8c35c8271e6ef4a - languageName: node - linkType: hard - -"error-ex@npm:^1.2.0, error-ex@npm:^1.3.1": - version: 1.3.2 - resolution: "error-ex@npm:1.3.2" - dependencies: - is-arrayish: ^0.2.1 - checksum: c1c2b8b65f9c91b0f9d75f0debaa7ec5b35c266c2cac5de412c1a6de86d4cbae04ae44e510378cb14d032d0645a36925d0186f8bb7367bcc629db256b743a001 - languageName: node - linkType: hard - -"es-abstract@npm:^1.19.0, es-abstract@npm:^1.19.1": - version: 1.19.1 - resolution: "es-abstract@npm:1.19.1" - dependencies: - call-bind: ^1.0.2 - es-to-primitive: ^1.2.1 - function-bind: ^1.1.1 - get-intrinsic: ^1.1.1 - get-symbol-description: ^1.0.0 - has: ^1.0.3 - has-symbols: ^1.0.2 - internal-slot: ^1.0.3 - is-callable: ^1.2.4 - is-negative-zero: ^2.0.1 - is-regex: ^1.1.4 - is-shared-array-buffer: ^1.0.1 - is-string: ^1.0.7 - is-weakref: ^1.0.1 - object-inspect: ^1.11.0 - object-keys: ^1.1.1 - object.assign: ^4.1.2 - string.prototype.trimend: ^1.0.4 - string.prototype.trimstart: ^1.0.4 - unbox-primitive: ^1.0.1 - checksum: b6be8410672c5364db3fb01eb786e30c7b4bb32b4af63d381c08840f4382c4a168e7855cd338bf59d4f1a1a1138f4d748d1fd40ec65aaa071876f9e9fbfed949 - languageName: node - linkType: hard - -"es-abstract@npm:^1.19.2, es-abstract@npm:^1.19.5, es-abstract@npm:^1.20.0, es-abstract@npm:^1.20.1": - version: 1.20.4 - resolution: "es-abstract@npm:1.20.4" - dependencies: - call-bind: ^1.0.2 - es-to-primitive: ^1.2.1 - function-bind: ^1.1.1 - function.prototype.name: ^1.1.5 - get-intrinsic: ^1.1.3 - get-symbol-description: ^1.0.0 - has: ^1.0.3 - has-property-descriptors: ^1.0.0 - has-symbols: ^1.0.3 - internal-slot: ^1.0.3 - is-callable: ^1.2.7 - is-negative-zero: ^2.0.2 - is-regex: ^1.1.4 - is-shared-array-buffer: ^1.0.2 - is-string: ^1.0.7 - is-weakref: ^1.0.2 - object-inspect: ^1.12.2 - object-keys: ^1.1.1 - object.assign: ^4.1.4 - regexp.prototype.flags: ^1.4.3 - safe-regex-test: ^1.0.0 - string.prototype.trimend: ^1.0.5 - string.prototype.trimstart: ^1.0.5 - unbox-primitive: ^1.0.2 - checksum: 89297cc785c31aedf961a603d5a07ed16471e435d3a1b6d070b54f157cf48454b95cda2ac55e4b86ff4fe3276e835fcffd2771578e6fa634337da49b26826141 - languageName: node - linkType: hard - -"es-abstract@npm:^1.22.1": - version: 1.22.2 - resolution: "es-abstract@npm:1.22.2" - dependencies: - array-buffer-byte-length: ^1.0.0 - arraybuffer.prototype.slice: ^1.0.2 - available-typed-arrays: ^1.0.5 - call-bind: ^1.0.2 - es-set-tostringtag: ^2.0.1 - es-to-primitive: ^1.2.1 - function.prototype.name: ^1.1.6 - get-intrinsic: ^1.2.1 - get-symbol-description: ^1.0.0 - globalthis: ^1.0.3 - gopd: ^1.0.1 - has: ^1.0.3 - has-property-descriptors: ^1.0.0 - has-proto: ^1.0.1 - has-symbols: ^1.0.3 - internal-slot: ^1.0.5 - is-array-buffer: ^3.0.2 - is-callable: ^1.2.7 - is-negative-zero: ^2.0.2 - is-regex: ^1.1.4 - is-shared-array-buffer: ^1.0.2 - is-string: ^1.0.7 - is-typed-array: ^1.1.12 - is-weakref: ^1.0.2 - object-inspect: ^1.12.3 - object-keys: ^1.1.1 - object.assign: ^4.1.4 - regexp.prototype.flags: ^1.5.1 - safe-array-concat: ^1.0.1 - safe-regex-test: ^1.0.0 - string.prototype.trim: ^1.2.8 - string.prototype.trimend: ^1.0.7 - string.prototype.trimstart: ^1.0.7 - typed-array-buffer: ^1.0.0 - typed-array-byte-length: ^1.0.0 - typed-array-byte-offset: ^1.0.0 - typed-array-length: ^1.0.4 - unbox-primitive: ^1.0.2 - which-typed-array: ^1.1.11 - checksum: cc70e592d360d7d729859013dee7a610c6b27ed8630df0547c16b0d16d9fe6505a70ee14d1af08d970fdd132b3f88c9ca7815ce72c9011608abf8ab0e55fc515 - languageName: node - linkType: hard - -"es-array-method-boxes-properly@npm:^1.0.0": - version: 1.0.0 - resolution: "es-array-method-boxes-properly@npm:1.0.0" - checksum: 2537fcd1cecf187083890bc6f5236d3a26bf39237433587e5bf63392e88faae929dbba78ff0120681a3f6f81c23fe3816122982c160d63b38c95c830b633b826 - languageName: node - linkType: hard - -"es-set-tostringtag@npm:^2.0.1": - version: 2.0.1 - resolution: "es-set-tostringtag@npm:2.0.1" - dependencies: - get-intrinsic: ^1.1.3 - has: ^1.0.3 - has-tostringtag: ^1.0.0 - checksum: ec416a12948cefb4b2a5932e62093a7cf36ddc3efd58d6c58ca7ae7064475ace556434b869b0bbeb0c365f1032a8ccd577211101234b69837ad83ad204fff884 - languageName: node - linkType: hard - -"es-shim-unscopables@npm:^1.0.0": - version: 1.0.0 - resolution: "es-shim-unscopables@npm:1.0.0" - dependencies: - has: ^1.0.3 - checksum: 83e95cadbb6ee44d3644dfad60dcad7929edbc42c85e66c3e99aefd68a3a5c5665f2686885cddb47dfeabfd77bd5ea5a7060f2092a955a729bbd8834f0d86fa1 - languageName: node - linkType: hard - -"es-to-primitive@npm:^1.2.1": - version: 1.2.1 - resolution: "es-to-primitive@npm:1.2.1" - dependencies: - is-callable: ^1.1.4 - is-date-object: ^1.0.1 - is-symbol: ^1.0.2 - checksum: 4ead6671a2c1402619bdd77f3503991232ca15e17e46222b0a41a5d81aebc8740a77822f5b3c965008e631153e9ef0580540007744521e72de8e33599fca2eed - languageName: node - linkType: hard - -"es5-ext@npm:^0.10.35, es5-ext@npm:^0.10.50": - version: 0.10.62 - resolution: "es5-ext@npm:0.10.62" - dependencies: - es6-iterator: ^2.0.3 - es6-symbol: ^3.1.3 - next-tick: ^1.1.0 - checksum: 25f42f6068cfc6e393cf670bc5bba249132c5f5ec2dd0ed6e200e6274aca2fed8e9aec8a31c76031744c78ca283c57f0b41c7e737804c6328c7b8d3fbcba7983 - languageName: node - linkType: hard - -"es6-iterator@npm:^2.0.3": - version: 2.0.3 - resolution: "es6-iterator@npm:2.0.3" - dependencies: - d: 1 - es5-ext: ^0.10.35 - es6-symbol: ^3.1.1 - checksum: 6e48b1c2d962c21dee604b3d9f0bc3889f11ed5a8b33689155a2065d20e3107e2a69cc63a71bd125aeee3a589182f8bbcb5c8a05b6a8f38fa4205671b6d09697 - languageName: node - linkType: hard - -"es6-promise@npm:^4.0.3, es6-promise@npm:^4.2.8": - version: 4.2.8 - resolution: "es6-promise@npm:4.2.8" - checksum: 95614a88873611cb9165a85d36afa7268af5c03a378b35ca7bda9508e1d4f1f6f19a788d4bc755b3fd37c8ebba40782018e02034564ff24c9d6fa37e959ad57d - languageName: node - linkType: hard - -"es6-promisify@npm:^5.0.0": - version: 5.0.0 - resolution: "es6-promisify@npm:5.0.0" - dependencies: - es6-promise: ^4.0.3 - checksum: fbed9d791598831413be84a5374eca8c24800ec71a16c1c528c43a98e2dadfb99331483d83ae6094ddb9b87e6f799a15d1553cebf756047e0865c753bc346b92 - languageName: node - linkType: hard - -"es6-symbol@npm:^3.1.1, es6-symbol@npm:^3.1.3": - version: 3.1.3 - resolution: "es6-symbol@npm:3.1.3" - dependencies: - d: ^1.0.1 - ext: ^1.1.2 - checksum: cd49722c2a70f011eb02143ef1c8c70658d2660dead6641e160b94619f408b9cf66425515787ffe338affdf0285ad54f4eae30ea5bd510e33f8659ec53bcaa70 - languageName: node - linkType: hard - -"escalade@npm:^3.1.1": - version: 3.1.1 - resolution: "escalade@npm:3.1.1" - checksum: a3e2a99f07acb74b3ad4989c48ca0c3140f69f923e56d0cba0526240ee470b91010f9d39001f2a4a313841d237ede70a729e92125191ba5d21e74b106800b133 - languageName: node - linkType: hard - -"escape-html@npm:~1.0.3": - version: 1.0.3 - resolution: "escape-html@npm:1.0.3" - checksum: 6213ca9ae00d0ab8bccb6d8d4e0a98e76237b2410302cf7df70aaa6591d509a2a37ce8998008cbecae8fc8ffaadf3fb0229535e6a145f3ce0b211d060decbb24 - languageName: node - linkType: hard - -"escape-string-regexp@npm:1.0.5, escape-string-regexp@npm:^1.0.2, escape-string-regexp@npm:^1.0.5": - version: 1.0.5 - resolution: "escape-string-regexp@npm:1.0.5" - checksum: 6092fda75c63b110c706b6a9bfde8a612ad595b628f0bd2147eea1d3406723020810e591effc7db1da91d80a71a737a313567c5abb3813e8d9c71f4aa595b410 - languageName: node - linkType: hard - -"escape-string-regexp@npm:4.0.0, escape-string-regexp@npm:^4.0.0": - version: 4.0.0 - resolution: "escape-string-regexp@npm:4.0.0" - checksum: 98b48897d93060f2322108bf29db0feba7dd774be96cd069458d1453347b25ce8682ecc39859d4bca2203cc0ab19c237bcc71755eff49a0f8d90beadeeba5cc5 - languageName: node - linkType: hard - -"escodegen@npm:1.8.x": - version: 1.8.1 - resolution: "escodegen@npm:1.8.1" - dependencies: - esprima: ^2.7.1 - estraverse: ^1.9.1 - esutils: ^2.0.2 - optionator: ^0.8.1 - source-map: ~0.2.0 - dependenciesMeta: - source-map: - optional: true - bin: - escodegen: ./bin/escodegen.js - esgenerate: ./bin/esgenerate.js - checksum: 99f5579dbc309d8f95f8051cce2f85620c073ff1d4f7b58197addee7e81aeb5281dadfbd446a0885b8fb8c0c47ce5c2cdb5f97dbfddccb5126cca5eb9af73992 - languageName: node - linkType: hard - -"eslint-config-prettier@npm:^8.3.0": - version: 8.3.0 - resolution: "eslint-config-prettier@npm:8.3.0" - peerDependencies: - eslint: ">=7.0.0" - bin: - eslint-config-prettier: bin/cli.js - checksum: df4cea3032671995bb5ab07e016169072f7fa59f44a53251664d9ca60951b66cdc872683b5c6a3729c91497c11490ca44a79654b395dd6756beb0c3903a37196 - languageName: node - linkType: hard - -"eslint-config-standard-kit@npm:0.15.1": - version: 0.15.1 - resolution: "eslint-config-standard-kit@npm:0.15.1" - checksum: da4a34544f0ea0325d0340c78cb625e785aa4c7121fa25805c11290fb62f7a3573f61b783957245050b6c0901e30618c508d2df4984a1ba120c0fe93f3773131 - languageName: node - linkType: hard - -"eslint-import-resolver-node@npm:^0.3.6": - version: 0.3.6 - resolution: "eslint-import-resolver-node@npm:0.3.6" - dependencies: - debug: ^3.2.7 - resolve: ^1.20.0 - checksum: 6266733af1e112970e855a5bcc2d2058fb5ae16ad2a6d400705a86b29552b36131ffc5581b744c23d550de844206fb55e9193691619ee4dbf225c4bde526b1c8 - languageName: node - linkType: hard - -"eslint-module-utils@npm:^2.7.0": - version: 2.7.1 - resolution: "eslint-module-utils@npm:2.7.1" - dependencies: - debug: ^3.2.7 - find-up: ^2.1.0 - pkg-dir: ^2.0.0 - checksum: c30dfa125aafe65e5f6a30a31c26932106fcf09934a2f47d7f8a393ed9106da7b07416f2337b55c85f9db0175c873ee0827be5429a24ec381b49940f342b9ac3 - languageName: node - linkType: hard - -"eslint-plugin-es@npm:^3.0.0": - version: 3.0.1 - resolution: "eslint-plugin-es@npm:3.0.1" - dependencies: - eslint-utils: ^2.0.0 - regexpp: ^3.0.0 - peerDependencies: - eslint: ">=4.19.1" - checksum: e57592c52301ee8ddc296ae44216df007f3a870bcb3be8d1fbdb909a1d3a3efe3fa3785de02066f9eba1d6466b722d3eb3cc3f8b75b3cf6a1cbded31ac6298e4 - languageName: node - linkType: hard - -"eslint-plugin-import@npm:^2.25.2": - version: 2.25.2 - resolution: "eslint-plugin-import@npm:2.25.2" - dependencies: - array-includes: ^3.1.4 - array.prototype.flat: ^1.2.5 - debug: ^2.6.9 - doctrine: ^2.1.0 - eslint-import-resolver-node: ^0.3.6 - eslint-module-utils: ^2.7.0 - has: ^1.0.3 - is-core-module: ^2.7.0 - is-glob: ^4.0.3 - minimatch: ^3.0.4 - object.values: ^1.1.5 - resolve: ^1.20.0 - tsconfig-paths: ^3.11.0 - peerDependencies: - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 - checksum: 4ca36e37faf72fb1ed25361ea8a6abbcc9daa65f3a9ac1dc0a660029000456e8c8b98a87b8cc2316541b13c6e5915df41d2dc4a1d7fe0729d9b72b9a3bd5b909 - languageName: node - linkType: hard - -"eslint-plugin-node@npm:^11.1.0": - version: 11.1.0 - resolution: "eslint-plugin-node@npm:11.1.0" - dependencies: - eslint-plugin-es: ^3.0.0 - eslint-utils: ^2.0.0 - ignore: ^5.1.1 - minimatch: ^3.0.4 - resolve: ^1.10.1 - semver: ^6.1.0 - peerDependencies: - eslint: ">=5.16.0" - checksum: 5804c4f8a6e721f183ef31d46fbe3b4e1265832f352810060e0502aeac7de034df83352fc88643b19641bb2163f2587f1bd4119aff0fd21e8d98c57c450e013b - languageName: node - linkType: hard - -"eslint-plugin-prettier@npm:^4.0.0": - version: 4.0.0 - resolution: "eslint-plugin-prettier@npm:4.0.0" - dependencies: - prettier-linter-helpers: ^1.0.0 - peerDependencies: - eslint: ">=7.28.0" - prettier: ">=2.0.0" - peerDependenciesMeta: - eslint-config-prettier: - optional: true - checksum: 03d69177a3c21fa2229c7e427ce604429f0b20ab7f411e2e824912f572a207c7f5a41fd1f0a95b9b8afe121e291c1b1f1dc1d44c7aad4b0837487f9c19f5210d - languageName: node - linkType: hard - -"eslint-plugin-simple-import-sort@npm:^7.0.0": - version: 7.0.0 - resolution: "eslint-plugin-simple-import-sort@npm:7.0.0" - peerDependencies: - eslint: ">=5.0.0" - checksum: 6aacb7179c213cd2081950630368d1f3b1dcb4f5674d8b989fe7839e7b317ee521d74761676e8b1a7cab49f20405dbcc9aac05358ae804e6bcba6cbf1daccb3d - languageName: node - linkType: hard - -"eslint-plugin-unused-imports@npm:^2.0.0": - version: 2.0.0 - resolution: "eslint-plugin-unused-imports@npm:2.0.0" - dependencies: - eslint-rule-composer: ^0.3.0 - peerDependencies: - "@typescript-eslint/eslint-plugin": ^5.0.0 - eslint: ^8.0.0 - peerDependenciesMeta: - "@typescript-eslint/eslint-plugin": - optional: true - checksum: 8aa1e03e75da2a62a354065e0cb8fe370118c6f8d9720a32fe8c1da937de6adb81a4fed7d0d391d115ac9453b49029fb19f970d180a2cf3dba451fd4c20f0dc4 - languageName: node - linkType: hard - -"eslint-rule-composer@npm:^0.3.0": - version: 0.3.0 - resolution: "eslint-rule-composer@npm:0.3.0" - checksum: c2f57cded8d1c8f82483e0ce28861214347e24fd79fd4144667974cd334d718f4ba05080aaef2399e3bbe36f7d6632865110227e6b176ed6daa2d676df9281b1 - languageName: node - linkType: hard - -"eslint-scope@npm:^4.0.3": - version: 4.0.3 - resolution: "eslint-scope@npm:4.0.3" - dependencies: - esrecurse: ^4.1.0 - estraverse: ^4.1.1 - checksum: c5f835f681884469991fe58d76a554688d9c9e50811299ccd4a8f79993a039f5bcb0ee6e8de2b0017d97c794b5832ef3b21c9aac66228e3aa0f7a0485bcfb65b - languageName: node - linkType: hard - -"eslint-scope@npm:^5.1.1": - version: 5.1.1 - resolution: "eslint-scope@npm:5.1.1" - dependencies: - esrecurse: ^4.3.0 - estraverse: ^4.1.1 - checksum: 47e4b6a3f0cc29c7feedee6c67b225a2da7e155802c6ea13bbef4ac6b9e10c66cd2dcb987867ef176292bf4e64eccc680a49e35e9e9c669f4a02bac17e86abdb - languageName: node - linkType: hard - -"eslint-utils@npm:^1.3.1": - version: 1.4.3 - resolution: "eslint-utils@npm:1.4.3" - dependencies: - eslint-visitor-keys: ^1.1.0 - checksum: a20630e686034107138272f245c460f6d77705d1f4bb0628c1a1faf59fc800f441188916b3ec3b957394dc405aa200a3017dfa2b0fff0976e307a4e645a18d1e - languageName: node - linkType: hard - -"eslint-utils@npm:^2.0.0, eslint-utils@npm:^2.1.0": - version: 2.1.0 - resolution: "eslint-utils@npm:2.1.0" - dependencies: - eslint-visitor-keys: ^1.1.0 - checksum: 27500938f348da42100d9e6ad03ae29b3de19ba757ae1a7f4a087bdcf83ac60949bbb54286492ca61fac1f5f3ac8692dd21537ce6214240bf95ad0122f24d71d - languageName: node - linkType: hard - -"eslint-utils@npm:^3.0.0": - version: 3.0.0 - resolution: "eslint-utils@npm:3.0.0" - dependencies: - eslint-visitor-keys: ^2.0.0 - peerDependencies: - eslint: ">=5" - checksum: 0668fe02f5adab2e5a367eee5089f4c39033af20499df88fe4e6aba2015c20720404d8c3d6349b6f716b08fdf91b9da4e5d5481f265049278099c4c836ccb619 - languageName: node - linkType: hard - -"eslint-visitor-keys@npm:^1.0.0, eslint-visitor-keys@npm:^1.1.0, eslint-visitor-keys@npm:^1.3.0": - version: 1.3.0 - resolution: "eslint-visitor-keys@npm:1.3.0" - checksum: 37a19b712f42f4c9027e8ba98c2b06031c17e0c0a4c696cd429bd9ee04eb43889c446f2cd545e1ff51bef9593fcec94ecd2c2ef89129fcbbf3adadbef520376a - languageName: node - linkType: hard - -"eslint-visitor-keys@npm:^2.0.0": - version: 2.1.0 - resolution: "eslint-visitor-keys@npm:2.1.0" - checksum: e3081d7dd2611a35f0388bbdc2f5da60b3a3c5b8b6e928daffff7391146b434d691577aa95064c8b7faad0b8a680266bcda0a42439c18c717b80e6718d7e267d - languageName: node - linkType: hard - -"eslint-visitor-keys@npm:^3.0.0": - version: 3.0.0 - resolution: "eslint-visitor-keys@npm:3.0.0" - checksum: 352607f367a2e0e2f9f234e40d6d9b34c39399345b8a9f204e1343749ddfae505d8343909cba6c4abc2ca03add4cdc0530af5e98f870ad7183fc2a89458669e5 - languageName: node - linkType: hard - -"eslint@npm:^5.6.0": - version: 5.16.0 - resolution: "eslint@npm:5.16.0" - dependencies: - "@babel/code-frame": ^7.0.0 - ajv: ^6.9.1 - chalk: ^2.1.0 - cross-spawn: ^6.0.5 - debug: ^4.0.1 - doctrine: ^3.0.0 - eslint-scope: ^4.0.3 - eslint-utils: ^1.3.1 - eslint-visitor-keys: ^1.0.0 - espree: ^5.0.1 - esquery: ^1.0.1 - esutils: ^2.0.2 - file-entry-cache: ^5.0.1 - functional-red-black-tree: ^1.0.1 - glob: ^7.1.2 - globals: ^11.7.0 - ignore: ^4.0.6 - import-fresh: ^3.0.0 - imurmurhash: ^0.1.4 - inquirer: ^6.2.2 - js-yaml: ^3.13.0 - json-stable-stringify-without-jsonify: ^1.0.1 - levn: ^0.3.0 - lodash: ^4.17.11 - minimatch: ^3.0.4 - mkdirp: ^0.5.1 - natural-compare: ^1.4.0 - optionator: ^0.8.2 - path-is-inside: ^1.0.2 - progress: ^2.0.0 - regexpp: ^2.0.1 - semver: ^5.5.1 - strip-ansi: ^4.0.0 - strip-json-comments: ^2.0.1 - table: ^5.2.3 - text-table: ^0.2.0 - bin: - eslint: ./bin/eslint.js - checksum: 53c6b9420992df95f986dc031f76949edbea14bdeed4e40d8cda8970fbf0fc013c6d91b98f469b6477753e50c9af133c1a768e421a1c160ec2cac7a246e05494 - languageName: node - linkType: hard - -"eslint@npm:^7.32.0": - version: 7.32.0 - resolution: "eslint@npm:7.32.0" - dependencies: - "@babel/code-frame": 7.12.11 - "@eslint/eslintrc": ^0.4.3 - "@humanwhocodes/config-array": ^0.5.0 - ajv: ^6.10.0 - chalk: ^4.0.0 - cross-spawn: ^7.0.2 - debug: ^4.0.1 - doctrine: ^3.0.0 - enquirer: ^2.3.5 - escape-string-regexp: ^4.0.0 - eslint-scope: ^5.1.1 - eslint-utils: ^2.1.0 - eslint-visitor-keys: ^2.0.0 - espree: ^7.3.1 - esquery: ^1.4.0 - esutils: ^2.0.2 - fast-deep-equal: ^3.1.3 - file-entry-cache: ^6.0.1 - functional-red-black-tree: ^1.0.1 - glob-parent: ^5.1.2 - globals: ^13.6.0 - ignore: ^4.0.6 - import-fresh: ^3.0.0 - imurmurhash: ^0.1.4 - is-glob: ^4.0.0 - js-yaml: ^3.13.1 - json-stable-stringify-without-jsonify: ^1.0.1 - levn: ^0.4.1 - lodash.merge: ^4.6.2 - minimatch: ^3.0.4 - natural-compare: ^1.4.0 - optionator: ^0.9.1 - progress: ^2.0.0 - regexpp: ^3.1.0 - semver: ^7.2.1 - strip-ansi: ^6.0.0 - strip-json-comments: ^3.1.0 - table: ^6.0.9 - text-table: ^0.2.0 - v8-compile-cache: ^2.0.3 - bin: - eslint: bin/eslint.js - checksum: cc85af9985a3a11085c011f3d27abe8111006d34cc274291b3c4d7bea51a4e2ff6135780249becd919ba7f6d6d1ecc38a6b73dacb6a7be08d38453b344dc8d37 - languageName: node - linkType: hard - -"espree@npm:^5.0.1": - version: 5.0.1 - resolution: "espree@npm:5.0.1" - dependencies: - acorn: ^6.0.7 - acorn-jsx: ^5.0.0 - eslint-visitor-keys: ^1.0.0 - checksum: a091aac2bddf872484b0a7e779e3a1ffab32d1c55a6c4f99e483613a0149443531272c191eda1c7c827e32a9e10f6ce7ea6b131c7b3f4e12471fe618ebbc5b7e - languageName: node - linkType: hard - -"espree@npm:^7.3.0, espree@npm:^7.3.1": - version: 7.3.1 - resolution: "espree@npm:7.3.1" - dependencies: - acorn: ^7.4.0 - acorn-jsx: ^5.3.1 - eslint-visitor-keys: ^1.3.0 - checksum: aa9b50dcce883449af2e23bc2b8d9abb77118f96f4cb313935d6b220f77137eaef7724a83c3f6243b96bc0e4ab14766198e60818caad99f9519ae5a336a39b45 - languageName: node - linkType: hard - -"esprima@npm:2.7.x, esprima@npm:^2.7.1": - version: 2.7.3 - resolution: "esprima@npm:2.7.3" - bin: - esparse: ./bin/esparse.js - esvalidate: ./bin/esvalidate.js - checksum: 55584508dca0551885e62c3369bc4a783bd948b43e2f034f05c2a37f3ca398db99f072ab228234e9cab09af8dc8c65d6ca7de3a975f2a296b34d1a3aba7e89f1 - languageName: node - linkType: hard - -"esprima@npm:^4.0.0, esprima@npm:~4.0.0": - version: 4.0.1 - resolution: "esprima@npm:4.0.1" - bin: - esparse: ./bin/esparse.js - esvalidate: ./bin/esvalidate.js - checksum: b45bc805a613dbea2835278c306b91aff6173c8d034223fa81498c77dcbce3b2931bf6006db816f62eacd9fd4ea975dfd85a5b7f3c6402cfd050d4ca3c13a628 - languageName: node - linkType: hard - -"esquery@npm:^1.0.1, esquery@npm:^1.4.0": - version: 1.4.0 - resolution: "esquery@npm:1.4.0" - dependencies: - estraverse: ^5.1.0 - checksum: a0807e17abd7fbe5fbd4fab673038d6d8a50675cdae6b04fbaa520c34581be0c5fa24582990e8acd8854f671dd291c78bb2efb9e0ed5b62f33bac4f9cf820210 - languageName: node - linkType: hard - -"esrecurse@npm:^4.1.0, esrecurse@npm:^4.3.0": - version: 4.3.0 - resolution: "esrecurse@npm:4.3.0" - dependencies: - estraverse: ^5.2.0 - checksum: ebc17b1a33c51cef46fdc28b958994b1dc43cd2e86237515cbc3b4e5d2be6a811b2315d0a1a4d9d340b6d2308b15322f5c8291059521cc5f4802f65e7ec32837 - languageName: node - linkType: hard - -"estraverse@npm:^1.9.1": - version: 1.9.3 - resolution: "estraverse@npm:1.9.3" - checksum: 78fa96317500e7783d48297dbd4c7f8735ddeb970be2981b485639ffa77578d05b8f781332622e436f2e9e533f32923c62c2e6463291e577ceeaf2776ac5e4b5 - languageName: node - linkType: hard - -"estraverse@npm:^4.1.1": - version: 4.3.0 - resolution: "estraverse@npm:4.3.0" - checksum: a6299491f9940bb246124a8d44b7b7a413a8336f5436f9837aaa9330209bd9ee8af7e91a654a3545aee9c54b3308e78ee360cef1d777d37cfef77d2fa33b5827 - languageName: node - linkType: hard - -"estraverse@npm:^5.1.0, estraverse@npm:^5.2.0": - version: 5.2.0 - resolution: "estraverse@npm:5.2.0" - checksum: ec11b70d946bf5d7f76f91db38ef6f08109ac1b36cda293a26e678e58df4719f57f67b9ec87042afdd1f0267cee91865be3aa48d2161765a93defab5431be7b8 - languageName: node - linkType: hard - -"esutils@npm:^2.0.2": - version: 2.0.3 - resolution: "esutils@npm:2.0.3" - checksum: 22b5b08f74737379a840b8ed2036a5fb35826c709ab000683b092d9054e5c2a82c27818f12604bfc2a9a76b90b6834ef081edbc1c7ae30d1627012e067c6ec87 - languageName: node - linkType: hard - -"etag@npm:~1.8.1": - version: 1.8.1 - resolution: "etag@npm:1.8.1" - checksum: 571aeb3dbe0f2bbd4e4fadbdb44f325fc75335cd5f6f6b6a091e6a06a9f25ed5392f0863c5442acb0646787446e816f13cbfc6edce5b07658541dff573cab1ff - languageName: node - linkType: hard - -"eth-block-tracker@npm:^3.0.0": - version: 3.0.1 - resolution: "eth-block-tracker@npm:3.0.1" - dependencies: - eth-query: ^2.1.0 - ethereumjs-tx: ^1.3.3 - ethereumjs-util: ^5.1.3 - ethjs-util: ^0.1.3 - json-rpc-engine: ^3.6.0 - pify: ^2.3.0 - tape: ^4.6.3 - checksum: b68dda7a60e2c15fa7097f31277ebfce08852de83229c2c65879a5482db28610bc85248cfe6578971ad2357552d5ce6124fb0c2a29d18fd30c70f092beeda3b8 - languageName: node - linkType: hard - -"eth-ens-namehash@npm:2.0.8, eth-ens-namehash@npm:^2.0.8": - version: 2.0.8 - resolution: "eth-ens-namehash@npm:2.0.8" - dependencies: - idna-uts46-hx: ^2.3.1 - js-sha3: ^0.5.7 - checksum: 40ce4aeedaa4e7eb4485c8d8857457ecc46a4652396981d21b7e3a5f922d5beff63c71cb4b283c935293e530eba50b329d9248be3c433949c6bc40c850c202a3 - languageName: node - linkType: hard - -"eth-gas-reporter@npm:^0.2.25": - version: 0.2.25 - resolution: "eth-gas-reporter@npm:0.2.25" - dependencies: - "@ethersproject/abi": ^5.0.0-beta.146 - "@solidity-parser/parser": ^0.14.0 - cli-table3: ^0.5.0 - colors: 1.4.0 - ethereum-cryptography: ^1.0.3 - ethers: ^4.0.40 - fs-readdir-recursive: ^1.1.0 - lodash: ^4.17.14 - markdown-table: ^1.1.3 - mocha: ^7.1.1 - req-cwd: ^2.0.0 - request: ^2.88.0 - request-promise-native: ^1.0.5 - sha1: ^1.1.1 - sync-request: ^6.0.0 - peerDependencies: - "@codechecks/client": ^0.1.0 - peerDependenciesMeta: - "@codechecks/client": - optional: true - checksum: 3bfa81e554b069bb817f2a073a601a0429e6b582c56ad99db0727dc2a102ab00fc27888820b8a042a194a8fb7d40954d10cd7b011ede6b8170285d2d5a88666c - languageName: node - linkType: hard - -"eth-json-rpc-infura@npm:^3.1.0": - version: 3.2.1 - resolution: "eth-json-rpc-infura@npm:3.2.1" - dependencies: - cross-fetch: ^2.1.1 - eth-json-rpc-middleware: ^1.5.0 - json-rpc-engine: ^3.4.0 - json-rpc-error: ^2.0.0 - checksum: 393e825986c0eedb9a1bb771b84e5b7c4037d8f870ab92cdba9dbaa52b5c7d5755ed02fd80d2a07b5db7a3af2c0b30d37756eb39cd7d2ae39173c6c2ea138e7d - languageName: node - linkType: hard - -"eth-json-rpc-middleware@npm:^1.5.0": - version: 1.6.0 - resolution: "eth-json-rpc-middleware@npm:1.6.0" - dependencies: - async: ^2.5.0 - eth-query: ^2.1.2 - eth-tx-summary: ^3.1.2 - ethereumjs-block: ^1.6.0 - ethereumjs-tx: ^1.3.3 - ethereumjs-util: ^5.1.2 - ethereumjs-vm: ^2.1.0 - fetch-ponyfill: ^4.0.0 - json-rpc-engine: ^3.6.0 - json-rpc-error: ^2.0.0 - json-stable-stringify: ^1.0.1 - promise-to-callback: ^1.0.0 - tape: ^4.6.3 - checksum: 0f6c146bdb277b3be9eef68f7424e1709a57f58330a3ae076153313be60f5026a5eee0de16d1ee6e41515e76cb1d38ef590948dd55d4b3ab1b3659af61337922 - languageName: node - linkType: hard - -"eth-lib@npm:0.2.8": - version: 0.2.8 - resolution: "eth-lib@npm:0.2.8" - dependencies: - bn.js: ^4.11.6 - elliptic: ^6.4.0 - xhr-request-promise: ^0.1.2 - checksum: be7efb0b08a78e20d12d2892363ecbbc557a367573ac82fc26a549a77a1b13c7747e6eadbb88026634828fcf9278884b555035787b575b1cab5e6958faad0fad - languageName: node - linkType: hard - -"eth-lib@npm:^0.1.26": - version: 0.1.29 - resolution: "eth-lib@npm:0.1.29" - dependencies: - bn.js: ^4.11.6 - elliptic: ^6.4.0 - nano-json-stream-parser: ^0.1.2 - servify: ^0.1.12 - ws: ^3.0.0 - xhr-request-promise: ^0.1.2 - checksum: d1494fc0af372d46d1c9e7506cfbfa81b9073d98081cf4cbe518932f88bee40cf46a764590f1f8aba03d4a534fa2b1cd794fa2a4f235f656d82b8ab185b5cb9d - languageName: node - linkType: hard - -"eth-query@npm:^2.0.2, eth-query@npm:^2.1.0, eth-query@npm:^2.1.2": - version: 2.1.2 - resolution: "eth-query@npm:2.1.2" - dependencies: - json-rpc-random-id: ^1.0.0 - xtend: ^4.0.1 - checksum: 83daa0e28452c54722aec78cd24d036bad5b6e7c08035d98e10d4bea11f71662f12cab63ebd8a848d4df46ad316503d54ecccb41c9244d2ea8b29364b0a20201 - languageName: node - linkType: hard - -"eth-sig-util@npm:3.0.0": - version: 3.0.0 - resolution: "eth-sig-util@npm:3.0.0" - dependencies: - buffer: ^5.2.1 - elliptic: ^6.4.0 - ethereumjs-abi: 0.6.5 - ethereumjs-util: ^5.1.1 - tweetnacl: ^1.0.0 - tweetnacl-util: ^0.15.0 - checksum: fbe44efb7909737b070e1e1d8c7096da3bdbd1356de242fc3458849e042e39c83a4e2dd1cbce0dc21ff3e5eca1843981751428bc160dcf3a6fcca2f1e8161be4 - languageName: node - linkType: hard - -"eth-sig-util@npm:^1.4.2": - version: 1.4.2 - resolution: "eth-sig-util@npm:1.4.2" - dependencies: - ethereumjs-abi: "git+https://github.com/ethereumjs/ethereumjs-abi.git" - ethereumjs-util: ^5.1.1 - checksum: 578f5c571c1bb0a86dc1bd4a5b56b8073b37823496d7afa74d772cf91ae6860f91bafcbee931be39a3d13f0c195df9f026a27fce350605ad5d15901a5a4ea94a - languageName: node - linkType: hard - -"eth-sig-util@npm:^3.0.1": - version: 3.0.1 - resolution: "eth-sig-util@npm:3.0.1" - dependencies: - ethereumjs-abi: ^0.6.8 - ethereumjs-util: ^5.1.1 - tweetnacl: ^1.0.3 - tweetnacl-util: ^0.15.0 - checksum: 614bf7011b30f78c3532f53e3f80919fe5502b0fa7a3656e6e7dae56d26bc9f559c5b6480c2bcc66d63cd9f72b489732df3b7f1daa0ac9a1fe3b6878347ab4c6 - languageName: node - linkType: hard - -"eth-tx-summary@npm:^3.1.2": - version: 3.2.4 - resolution: "eth-tx-summary@npm:3.2.4" - dependencies: - async: ^2.1.2 - clone: ^2.0.0 - concat-stream: ^1.5.1 - end-of-stream: ^1.1.0 - eth-query: ^2.0.2 - ethereumjs-block: ^1.4.1 - ethereumjs-tx: ^1.1.1 - ethereumjs-util: ^5.0.1 - ethereumjs-vm: ^2.6.0 - through2: ^2.0.3 - checksum: 7df8b91bc2bd3f6941e2a5b3230cad5c5523ca3750190cd06af07983feba1bb4af893f226f01072958b00aa626869846894bcb1bfaa451d9c8f7f5b8cdf5ce0a - languageName: node - linkType: hard - -"ethashjs@npm:~0.0.7": - version: 0.0.8 - resolution: "ethashjs@npm:0.0.8" - dependencies: - async: ^2.1.2 - buffer-xor: ^2.0.1 - ethereumjs-util: ^7.0.2 - miller-rabin: ^4.0.0 - checksum: d9b6b47d32cbe017848ce5d8aec86eb6416300c6f52a68029bf6fc8fcf5429a45c14f2033d514435acd02047af16f6f804056e81587b30ed677039ac678b15f8 - languageName: node - linkType: hard - -"ethereum-bloom-filters@npm:^1.0.6": - version: 1.0.10 - resolution: "ethereum-bloom-filters@npm:1.0.10" - dependencies: - js-sha3: ^0.8.0 - checksum: 4019cc6f9274ae271a52959194a72f6e9b013366f168f922dc3b349319faf7426bf1010125ee0676b4f75714fe4a440edd4e7e62342c121a046409f4cd4c0af9 - languageName: node - linkType: hard - -"ethereum-common@npm:0.2.0": - version: 0.2.0 - resolution: "ethereum-common@npm:0.2.0" - checksum: 5e80af27482530ac700676502cd4c02a7248c064999d01dced302f5f40a180c86f57caaab347dbd12482c2869539d321c8c0039db9e3dfb1411e6ad3d57b2547 - languageName: node - linkType: hard - -"ethereum-common@npm:^0.0.18": - version: 0.0.18 - resolution: "ethereum-common@npm:0.0.18" - checksum: 2244126199604abc17508ca249c6f8a66a2ed02e9c97115f234e311f42e2d67aedff08128569fa3dfb8a2d09e1c194eace39a1ce61bfeb2338b6d3f2ac324ee8 - languageName: node - linkType: hard - -"ethereum-cryptography@npm:0.1.3, ethereum-cryptography@npm:^0.1.3": - version: 0.1.3 - resolution: "ethereum-cryptography@npm:0.1.3" - dependencies: - "@types/pbkdf2": ^3.0.0 - "@types/secp256k1": ^4.0.1 - blakejs: ^1.1.0 - browserify-aes: ^1.2.0 - bs58check: ^2.1.2 - create-hash: ^1.2.0 - create-hmac: ^1.1.7 - hash.js: ^1.1.7 - keccak: ^3.0.0 - pbkdf2: ^3.0.17 - randombytes: ^2.1.0 - safe-buffer: ^5.1.2 - scrypt-js: ^3.0.0 - secp256k1: ^4.0.1 - setimmediate: ^1.0.5 - checksum: 54bae7a4a96bd81398cdc35c91cfcc74339f71a95ed1b5b694663782e69e8e3afd21357de3b8bac9ff4877fd6f043601e200a7ad9133d94be6fd7d898ee0a449 - languageName: node - linkType: hard - -"ethereum-cryptography@npm:^1.0.3": - version: 1.1.2 - resolution: "ethereum-cryptography@npm:1.1.2" - dependencies: - "@noble/hashes": 1.1.2 - "@noble/secp256k1": 1.6.3 - "@scure/bip32": 1.1.0 - "@scure/bip39": 1.1.0 - checksum: 0ef55f141acad45b1ba1db58ce3d487155eb2d0b14a77b3959167a36ad324f46762873257def75e7f00dbe8ac78aabc323d2207830f85e63a42a1fb67063a6ba - languageName: node - linkType: hard - -"ethereum-waffle@npm:^3.4.0": - version: 3.4.4 - resolution: "ethereum-waffle@npm:3.4.4" - dependencies: - "@ethereum-waffle/chai": ^3.4.4 - "@ethereum-waffle/compiler": ^3.4.4 - "@ethereum-waffle/mock-contract": ^3.4.4 - "@ethereum-waffle/provider": ^3.4.4 - ethers: ^5.0.1 - bin: - waffle: bin/waffle - checksum: 5a181b52f66f1b3c89ed1b68ef44cbd9acd4d743262de9edbe1fd57b0925576dd62c3436b1e65434d5ac03ab16da0df283972cd9aae726de0b8b9cdd7876b917 - languageName: node - linkType: hard - -"ethereumjs-abi@git+https://github.com/ethereumjs/ethereumjs-abi.git": - version: 0.6.8 - resolution: "ethereumjs-abi@https://github.com/ethereumjs/ethereumjs-abi.git#commit=ee3994657fa7a427238e6ba92a84d0b529bbcde0" - dependencies: - bn.js: ^4.11.8 - ethereumjs-util: ^6.0.0 - checksum: ae074be0bb012857ab5d3ae644d1163b908a48dd724b7d2567cfde309dc72222d460438f2411936a70dc949dc604ce1ef7118f7273bd525815579143c907e336 - languageName: node - linkType: hard - -"ethereumjs-abi@npm:0.6.5": - version: 0.6.5 - resolution: "ethereumjs-abi@npm:0.6.5" - dependencies: - bn.js: ^4.10.0 - ethereumjs-util: ^4.3.0 - checksum: 3abdc79dc60614d30b1cefb5e6bfbdab3ca8252b4e742330544103f86d6e49a55921d9b8822a0a47fee3efd9dd2493ec93448b1869d82479a4c71a44001e8337 - languageName: node - linkType: hard - -"ethereumjs-abi@npm:0.6.8, ethereumjs-abi@npm:^0.6.8": - version: 0.6.8 - resolution: "ethereumjs-abi@npm:0.6.8" - dependencies: - bn.js: ^4.11.8 - ethereumjs-util: ^6.0.0 - checksum: cede2a8ae7c7e04eeaec079c2f925601a25b2ef75cf9230e7c5da63b4ea27883b35447365a47e35c1e831af520973a2252af89022c292c18a09a4607821a366b - languageName: node - linkType: hard - -"ethereumjs-account@npm:3.0.0, ethereumjs-account@npm:^3.0.0": - version: 3.0.0 - resolution: "ethereumjs-account@npm:3.0.0" - dependencies: - ethereumjs-util: ^6.0.0 - rlp: ^2.2.1 - safe-buffer: ^5.1.1 - checksum: 64dbe026d29aca12c79596cf4085fb27e209988f11b7d5bf3a1f2aadaaa517d90d722680c8b525144c26a2d9cd8494aa26ac088fa80b358cc3e28024f7ddbe81 - languageName: node - linkType: hard - -"ethereumjs-account@npm:^2.0.3": - version: 2.0.5 - resolution: "ethereumjs-account@npm:2.0.5" - dependencies: - ethereumjs-util: ^5.0.0 - rlp: ^2.0.0 - safe-buffer: ^5.1.1 - checksum: 2e4546b8b0213168eebd3a5296da904b6f55470e39b4c742d252748927d2b268f8d6374b0178c1d5b7188646f97dae74a7ac1c7485fe96ea557c152b52223f18 - languageName: node - linkType: hard - -"ethereumjs-block@npm:2.2.2, ethereumjs-block@npm:^2.2.2, ethereumjs-block@npm:~2.2.0, ethereumjs-block@npm:~2.2.2": - version: 2.2.2 - resolution: "ethereumjs-block@npm:2.2.2" - dependencies: - async: ^2.0.1 - ethereumjs-common: ^1.5.0 - ethereumjs-tx: ^2.1.1 - ethereumjs-util: ^5.0.0 - merkle-patricia-tree: ^2.1.2 - checksum: 91f7f60820394e072c9a115da2871a096414644109d2449d4a79b30be67b0080bc848dfa7e2ae7b2ab255de3be4f6736c6cb2b418c29eada794d018cc384e189 - languageName: node - linkType: hard - -"ethereumjs-block@npm:^1.2.2, ethereumjs-block@npm:^1.4.1, ethereumjs-block@npm:^1.6.0": - version: 1.7.1 - resolution: "ethereumjs-block@npm:1.7.1" - dependencies: - async: ^2.0.1 - ethereum-common: 0.2.0 - ethereumjs-tx: ^1.2.2 - ethereumjs-util: ^5.0.0 - merkle-patricia-tree: ^2.1.2 - checksum: 9967c3674af77ea8475a3c023fa160ef6b614450ec50fa32ac083909ead22d3d1c3148f9407b6593d3ccfbe0c51f889c26aa1c15b17026fc2d35cbc542822af8 - languageName: node - linkType: hard - -"ethereumjs-blockchain@npm:^4.0.3": - version: 4.0.4 - resolution: "ethereumjs-blockchain@npm:4.0.4" - dependencies: - async: ^2.6.1 - ethashjs: ~0.0.7 - ethereumjs-block: ~2.2.2 - ethereumjs-common: ^1.5.0 - ethereumjs-util: ^6.1.0 - flow-stoplight: ^1.0.0 - level-mem: ^3.0.1 - lru-cache: ^5.1.1 - rlp: ^2.2.2 - semaphore: ^1.1.0 - checksum: efa04b2e2d02ce9c524f246f862b1ca779bbfd9f795cc7a9e471f0d96229de5188f1f6b17e54948f640100116b646ed03242494c23cd66f0f7e8384a4f217ba4 - languageName: node - linkType: hard - -"ethereumjs-common@npm:1.5.0": - version: 1.5.0 - resolution: "ethereumjs-common@npm:1.5.0" - checksum: a30474986a88b8f3ee53f9fb34027528f12d1bc7ecee8b80aa8060a09ccde3b2af4dd24c928287018003e4e206cd4f6311cdd508442d1452d02ec3d8e7a0601e - languageName: node - linkType: hard - -"ethereumjs-common@npm:^1.1.0, ethereumjs-common@npm:^1.3.2, ethereumjs-common@npm:^1.5.0": - version: 1.5.2 - resolution: "ethereumjs-common@npm:1.5.2" - checksum: 3fc64faced268e0c61da50c5db76d18cfd44325d5706792f32ac8c85c0e800d52db284f042c3bd0623daf59b946176ef7dbea476d1b0252492137fa4549a3349 - languageName: node - linkType: hard - -"ethereumjs-tx@npm:2.1.2, ethereumjs-tx@npm:^2.1.1, ethereumjs-tx@npm:^2.1.2": - version: 2.1.2 - resolution: "ethereumjs-tx@npm:2.1.2" - dependencies: - ethereumjs-common: ^1.5.0 - ethereumjs-util: ^6.0.0 - checksum: a5b607b4e125ed696d76a9e4db8a95e03a967323c66694912d799619b16fa43985336924221f9e7582dc1b09ff88a62116bf2290ee14d952bf7e6715e5728525 - languageName: node - linkType: hard - -"ethereumjs-tx@npm:^1.1.1, ethereumjs-tx@npm:^1.2.0, ethereumjs-tx@npm:^1.2.2, ethereumjs-tx@npm:^1.3.3": - version: 1.3.7 - resolution: "ethereumjs-tx@npm:1.3.7" - dependencies: - ethereum-common: ^0.0.18 - ethereumjs-util: ^5.0.0 - checksum: fe2323fe7db7f5dda85715dc67c31dd1f2925bf5a88e393ba939dbe699b73df008f1332f711b1aa37e943193acf3b6976202a33f2fab1f7675b6d2dd70f424d4 - languageName: node - linkType: hard - -"ethereumjs-util@npm:6.2.1, ethereumjs-util@npm:^6.0.0, ethereumjs-util@npm:^6.1.0, ethereumjs-util@npm:^6.2.0, ethereumjs-util@npm:^6.2.1": - version: 6.2.1 - resolution: "ethereumjs-util@npm:6.2.1" - dependencies: - "@types/bn.js": ^4.11.3 - bn.js: ^4.11.0 - create-hash: ^1.1.2 - elliptic: ^6.5.2 - ethereum-cryptography: ^0.1.3 - ethjs-util: 0.1.6 - rlp: ^2.2.3 - checksum: e3cb4a2c034a2529281fdfc21a2126fe032fdc3038863f5720352daa65ddcc50fc8c67dbedf381a882dc3802e05d979287126d7ecf781504bde1fd8218693bde - languageName: node - linkType: hard - -"ethereumjs-util@npm:^4.3.0": - version: 4.5.1 - resolution: "ethereumjs-util@npm:4.5.1" - dependencies: - bn.js: ^4.8.0 - create-hash: ^1.1.2 - elliptic: ^6.5.2 - ethereum-cryptography: ^0.1.3 - rlp: ^2.0.0 - checksum: ee91fbd29634d40cad9adf90f202158324c089bbc10b405d2ef139f4542090e6f76a616d16c601b52d6b5c5d59ddb6c8387cf60cc732884e732dad9a62b8a539 - languageName: node - linkType: hard - -"ethereumjs-util@npm:^5.0.0, ethereumjs-util@npm:^5.0.1, ethereumjs-util@npm:^5.1.1, ethereumjs-util@npm:^5.1.2, ethereumjs-util@npm:^5.1.3, ethereumjs-util@npm:^5.1.5, ethereumjs-util@npm:^5.2.0": - version: 5.2.1 - resolution: "ethereumjs-util@npm:5.2.1" - dependencies: - bn.js: ^4.11.0 - create-hash: ^1.1.2 - elliptic: ^6.5.2 - ethereum-cryptography: ^0.1.3 - ethjs-util: ^0.1.3 - rlp: ^2.0.0 - safe-buffer: ^5.1.1 - checksum: 20db6c639d92b35739fd5f7a71e64a92e85442ea0d176b59b5cd5828265b6cf42bd4868cf81a9b20a83738db1ffa7a2f778f1d850d663627a1a5209f7904b44f - languageName: node - linkType: hard - -"ethereumjs-util@npm:^7.0.10, ethereumjs-util@npm:^7.0.2, ethereumjs-util@npm:^7.0.3, ethereumjs-util@npm:^7.1.1, ethereumjs-util@npm:^7.1.4, ethereumjs-util@npm:^7.1.5": - version: 7.1.5 - resolution: "ethereumjs-util@npm:7.1.5" - dependencies: - "@types/bn.js": ^5.1.0 - bn.js: ^5.1.2 - create-hash: ^1.1.2 - ethereum-cryptography: ^0.1.3 - rlp: ^2.2.4 - checksum: 27a3c79d6e06b2df34b80d478ce465b371c8458b58f5afc14d91c8564c13363ad336e6e83f57eb0bd719fde94d10ee5697ceef78b5aa932087150c5287b286d1 - languageName: node - linkType: hard - -"ethereumjs-util@npm:^7.1.0": - version: 7.1.3 - resolution: "ethereumjs-util@npm:7.1.3" - dependencies: - "@types/bn.js": ^5.1.0 - bn.js: ^5.1.2 - create-hash: ^1.1.2 - ethereum-cryptography: ^0.1.3 - rlp: ^2.2.4 - checksum: 6de7a32af05c7265c96163ecd15ad97327afab9deb36092ef26250616657a8c0b5df8e698328247c8193e7b87c643c967f64f0b3cff2b2937cafa870ff5fcb41 - languageName: node - linkType: hard - -"ethereumjs-vm@npm:4.2.0": - version: 4.2.0 - resolution: "ethereumjs-vm@npm:4.2.0" - dependencies: - async: ^2.1.2 - async-eventemitter: ^0.2.2 - core-js-pure: ^3.0.1 - ethereumjs-account: ^3.0.0 - ethereumjs-block: ^2.2.2 - ethereumjs-blockchain: ^4.0.3 - ethereumjs-common: ^1.5.0 - ethereumjs-tx: ^2.1.2 - ethereumjs-util: ^6.2.0 - fake-merkle-patricia-tree: ^1.0.1 - functional-red-black-tree: ^1.0.1 - merkle-patricia-tree: ^2.3.2 - rustbn.js: ~0.2.0 - safe-buffer: ^5.1.1 - util.promisify: ^1.0.0 - checksum: ca73c406d55baefacafbdd8cefce80740098e5834096042e93285dc386ee670b4fed2f7846b78e3078fdf41231d04b3f1c40e435e639d072e0529ccb560b797b - languageName: node - linkType: hard - -"ethereumjs-vm@npm:^2.1.0, ethereumjs-vm@npm:^2.3.4, ethereumjs-vm@npm:^2.6.0": - version: 2.6.0 - resolution: "ethereumjs-vm@npm:2.6.0" - dependencies: - async: ^2.1.2 - async-eventemitter: ^0.2.2 - ethereumjs-account: ^2.0.3 - ethereumjs-block: ~2.2.0 - ethereumjs-common: ^1.1.0 - ethereumjs-util: ^6.0.0 - fake-merkle-patricia-tree: ^1.0.1 - functional-red-black-tree: ^1.0.1 - merkle-patricia-tree: ^2.3.2 - rustbn.js: ~0.2.0 - safe-buffer: ^5.1.1 - checksum: 3b3098b2ac3d5335797e4d73fceb76d1b776e453abb5fa4d1cd94f6391f493e95e3c89a8ee602558bc2a3b36b89977e66473de73faa87c8540b1954aa7b8c3fd - languageName: node - linkType: hard - -"ethereumjs-wallet@npm:0.6.5": - version: 0.6.5 - resolution: "ethereumjs-wallet@npm:0.6.5" - dependencies: - aes-js: ^3.1.1 - bs58check: ^2.1.2 - ethereum-cryptography: ^0.1.3 - ethereumjs-util: ^6.0.0 - randombytes: ^2.0.6 - safe-buffer: ^5.1.2 - scryptsy: ^1.2.1 - utf8: ^3.0.0 - uuid: ^3.3.2 - checksum: 54a9cc8beb8ea55e9be9b024b6ed09349423145fd8c49b8662d60d9258039330163c830fec055f92becc71ea54b430d2ef29f6bd73fa49d93ea854af01d13e58 - languageName: node - linkType: hard - -"ethers@npm:5.7.2, ethers@npm:^5.0.1, ethers@npm:^5.0.2, ethers@npm:^5.5.2, ethers@npm:^5.5.3, ethers@npm:^5.7.1, ethers@npm:^5.7.2": - version: 5.7.2 - resolution: "ethers@npm:5.7.2" - dependencies: - "@ethersproject/abi": 5.7.0 - "@ethersproject/abstract-provider": 5.7.0 - "@ethersproject/abstract-signer": 5.7.0 - "@ethersproject/address": 5.7.0 - "@ethersproject/base64": 5.7.0 - "@ethersproject/basex": 5.7.0 - "@ethersproject/bignumber": 5.7.0 - "@ethersproject/bytes": 5.7.0 - "@ethersproject/constants": 5.7.0 - "@ethersproject/contracts": 5.7.0 - "@ethersproject/hash": 5.7.0 - "@ethersproject/hdnode": 5.7.0 - "@ethersproject/json-wallets": 5.7.0 - "@ethersproject/keccak256": 5.7.0 - "@ethersproject/logger": 5.7.0 - "@ethersproject/networks": 5.7.1 - "@ethersproject/pbkdf2": 5.7.0 - "@ethersproject/properties": 5.7.0 - "@ethersproject/providers": 5.7.2 - "@ethersproject/random": 5.7.0 - "@ethersproject/rlp": 5.7.0 - "@ethersproject/sha2": 5.7.0 - "@ethersproject/signing-key": 5.7.0 - "@ethersproject/solidity": 5.7.0 - "@ethersproject/strings": 5.7.0 - "@ethersproject/transactions": 5.7.0 - "@ethersproject/units": 5.7.0 - "@ethersproject/wallet": 5.7.0 - "@ethersproject/web": 5.7.1 - "@ethersproject/wordlists": 5.7.0 - checksum: b7c08cf3e257185a7946117dbbf764433b7ba0e77c27298dec6088b3bc871aff711462b0621930c56880ff0a7ceb8b1d3a361ffa259f93377b48e34107f62553 - languageName: node - linkType: hard - -"ethers@npm:^4.0.32, ethers@npm:^4.0.40": - version: 4.0.49 - resolution: "ethers@npm:4.0.49" - dependencies: - aes-js: 3.0.0 - bn.js: ^4.11.9 - elliptic: 6.5.4 - hash.js: 1.1.3 - js-sha3: 0.5.7 - scrypt-js: 2.0.4 - setimmediate: 1.0.4 - uuid: 2.0.1 - xmlhttprequest: 1.8.0 - checksum: 357115348a5f1484c7745fae1d852876788216c7d94c072c80132192f1800c4d388433ea2456750856641d6d4eed8a3b41847eb44f5e1c42139963864e3bcc38 - languageName: node - linkType: hard - -"ethers@npm:^6.7.0": - version: 6.7.0 - resolution: "ethers@npm:6.7.0" - dependencies: - "@adraffy/ens-normalize": 1.9.2 - "@noble/hashes": 1.1.2 - "@noble/secp256k1": 1.7.1 - "@types/node": 18.15.13 - aes-js: 4.0.0-beta.5 - tslib: 2.4.0 - ws: 8.5.0 - checksum: 6d2ea085010da1c34750ce4a00a94d2abbeb3ababb23aa754acc7772682f145e8c1b3862d3b5374e1c182aee569c80ea48191107d469a4de3b0dd6af3d9ce6db - languageName: node - linkType: hard - -"ethjs-unit@npm:0.1.6": - version: 0.1.6 - resolution: "ethjs-unit@npm:0.1.6" - dependencies: - bn.js: 4.11.6 - number-to-bn: 1.7.0 - checksum: df6b4752ff7461a59a20219f4b1684c631ea601241c39660e3f6c6bd63c950189723841c22b3c6c0ebeb3c9fc99e0e803e3c613101206132603705fcbcf4def5 - languageName: node - linkType: hard - -"ethjs-util@npm:0.1.6, ethjs-util@npm:^0.1.3, ethjs-util@npm:^0.1.6": - version: 0.1.6 - resolution: "ethjs-util@npm:0.1.6" - dependencies: - is-hex-prefixed: 1.0.0 - strip-hex-prefix: 1.0.0 - checksum: 1f42959e78ec6f49889c49c8a98639e06f52a15966387dd39faf2930db48663d026efb7db2702dcffe7f2a99c4a0144b7ce784efdbf733f4077aae95de76d65f - languageName: node - linkType: hard - -"event-target-shim@npm:^5.0.0": - version: 5.0.1 - resolution: "event-target-shim@npm:5.0.1" - checksum: 1ffe3bb22a6d51bdeb6bf6f7cf97d2ff4a74b017ad12284cc9e6a279e727dc30a5de6bb613e5596ff4dc3e517841339ad09a7eec44266eccb1aa201a30448166 - languageName: node - linkType: hard - -"eventemitter3@npm:4.0.4": - version: 4.0.4 - resolution: "eventemitter3@npm:4.0.4" - checksum: 7afb1cd851d19898bc99cc55ca894fe18cb1f8a07b0758652830a09bd6f36082879a25345be6219b81d74764140688b1a8fa75bcd1073d96b9a6661e444bc2ea - languageName: node - linkType: hard - -"eventemitter3@npm:5.0.1": - version: 5.0.1 - resolution: "eventemitter3@npm:5.0.1" - checksum: 543d6c858ab699303c3c32e0f0f47fc64d360bf73c3daf0ac0b5079710e340d6fe9f15487f94e66c629f5f82cd1a8678d692f3dbb6f6fcd1190e1b97fcad36f8 - languageName: node - linkType: hard - -"events@npm:^3.0.0, events@npm:^3.3.0": - version: 3.3.0 - resolution: "events@npm:3.3.0" - checksum: f6f487ad2198aa41d878fa31452f1a3c00958f46e9019286ff4787c84aac329332ab45c9cdc8c445928fc6d7ded294b9e005a7fce9426488518017831b272780 - languageName: node - linkType: hard - -"evp_bytestokey@npm:^1.0.0, evp_bytestokey@npm:^1.0.3": - version: 1.0.3 - resolution: "evp_bytestokey@npm:1.0.3" - dependencies: - md5.js: ^1.3.4 - node-gyp: latest - safe-buffer: ^5.1.1 - checksum: ad4e1577f1a6b721c7800dcc7c733fe01f6c310732bb5bf2240245c2a5b45a38518b91d8be2c610611623160b9d1c0e91f1ce96d639f8b53e8894625cf20fa45 - languageName: node - linkType: hard - -"execa@npm:5.1.1": - version: 5.1.1 - resolution: "execa@npm:5.1.1" - dependencies: - cross-spawn: ^7.0.3 - get-stream: ^6.0.0 - human-signals: ^2.1.0 - is-stream: ^2.0.0 - merge-stream: ^2.0.0 - npm-run-path: ^4.0.1 - onetime: ^5.1.2 - signal-exit: ^3.0.3 - strip-final-newline: ^2.0.0 - checksum: fba9022c8c8c15ed862847e94c252b3d946036d7547af310e344a527e59021fd8b6bb0723883ea87044dc4f0201f949046993124a42ccb0855cae5bf8c786343 - languageName: node - linkType: hard - -"execa@npm:^1.0.0": - version: 1.0.0 - resolution: "execa@npm:1.0.0" - dependencies: - cross-spawn: ^6.0.0 - get-stream: ^4.0.0 - is-stream: ^1.1.0 - npm-run-path: ^2.0.0 - p-finally: ^1.0.0 - signal-exit: ^3.0.0 - strip-eof: ^1.0.0 - checksum: ddf1342c1c7d02dd93b41364cd847640f6163350d9439071abf70bf4ceb1b9b2b2e37f54babb1d8dc1df8e0d8def32d0e81e74a2e62c3e1d70c303eb4c306bc4 - languageName: node - linkType: hard - -"exit-hook@npm:^1.0.0": - version: 1.1.1 - resolution: "exit-hook@npm:1.1.1" - checksum: 1b4f16da7c202cd336ca07acb052922639182b4e2f1ad4007ed481bb774ce93469f505dec1371d9cd580ac54146a9fd260f053b0e4a48fa87c49fa3dc4a3f144 - languageName: node - linkType: hard - -"expand-brackets@npm:^2.1.4": - version: 2.1.4 - resolution: "expand-brackets@npm:2.1.4" - dependencies: - debug: ^2.3.3 - define-property: ^0.2.5 - extend-shallow: ^2.0.1 - posix-character-classes: ^0.1.0 - regex-not: ^1.0.0 - snapdragon: ^0.8.1 - to-regex: ^3.0.1 - checksum: 1781d422e7edfa20009e2abda673cadb040a6037f0bd30fcd7357304f4f0c284afd420d7622722ca4a016f39b6d091841ab57b401c1f7e2e5131ac65b9f14fa1 - languageName: node - linkType: hard - -"expand-template@npm:^2.0.3": - version: 2.0.3 - resolution: "expand-template@npm:2.0.3" - checksum: 588c19847216421ed92befb521767b7018dc88f88b0576df98cb242f20961425e96a92cbece525ef28cc5becceae5d544ae0f5b9b5e2aa05acb13716ca5b3099 - languageName: node - linkType: hard - -"express@npm:^4.14.0": - version: 4.18.2 - resolution: "express@npm:4.18.2" - dependencies: - accepts: ~1.3.8 - array-flatten: 1.1.1 - body-parser: 1.20.1 - content-disposition: 0.5.4 - content-type: ~1.0.4 - cookie: 0.5.0 - cookie-signature: 1.0.6 - debug: 2.6.9 - depd: 2.0.0 - encodeurl: ~1.0.2 - escape-html: ~1.0.3 - etag: ~1.8.1 - finalhandler: 1.2.0 - fresh: 0.5.2 - http-errors: 2.0.0 - merge-descriptors: 1.0.1 - methods: ~1.1.2 - on-finished: 2.4.1 - parseurl: ~1.3.3 - path-to-regexp: 0.1.7 - proxy-addr: ~2.0.7 - qs: 6.11.0 - range-parser: ~1.2.1 - safe-buffer: 5.2.1 - send: 0.18.0 - serve-static: 1.15.0 - setprototypeof: 1.2.0 - statuses: 2.0.1 - type-is: ~1.6.18 - utils-merge: 1.0.1 - vary: ~1.1.2 - checksum: 3c4b9b076879442f6b968fe53d85d9f1eeacbb4f4c41e5f16cc36d77ce39a2b0d81b3f250514982110d815b2f7173f5561367f9110fcc541f9371948e8c8b037 - languageName: node - linkType: hard - -"ext@npm:^1.1.2": - version: 1.7.0 - resolution: "ext@npm:1.7.0" - dependencies: - type: ^2.7.2 - checksum: ef481f9ef45434d8c867cfd09d0393b60945b7c8a1798bedc4514cb35aac342ccb8d8ecb66a513e6a2b4ec1e294a338e3124c49b29736f8e7c735721af352c31 - languageName: node - linkType: hard - -"extend-shallow@npm:^2.0.1": - version: 2.0.1 - resolution: "extend-shallow@npm:2.0.1" - dependencies: - is-extendable: ^0.1.0 - checksum: 8fb58d9d7a511f4baf78d383e637bd7d2e80843bd9cd0853649108ea835208fb614da502a553acc30208e1325240bb7cc4a68473021612496bb89725483656d8 - languageName: node - linkType: hard - -"extend-shallow@npm:^3.0.0, extend-shallow@npm:^3.0.2": - version: 3.0.2 - resolution: "extend-shallow@npm:3.0.2" - dependencies: - assign-symbols: ^1.0.0 - is-extendable: ^1.0.1 - checksum: a920b0cd5838a9995ace31dfd11ab5e79bf6e295aa566910ce53dff19f4b1c0fda2ef21f26b28586c7a2450ca2b42d97bd8c0f5cec9351a819222bf861e02461 - languageName: node - linkType: hard - -"extend@npm:~3.0.2": - version: 3.0.2 - resolution: "extend@npm:3.0.2" - checksum: a50a8309ca65ea5d426382ff09f33586527882cf532931cb08ca786ea3146c0553310bda688710ff61d7668eba9f96b923fe1420cdf56a2c3eaf30fcab87b515 - languageName: node - linkType: hard - -"external-editor@npm:^3.0.3": - version: 3.1.0 - resolution: "external-editor@npm:3.1.0" - dependencies: - chardet: ^0.7.0 - iconv-lite: ^0.4.24 - tmp: ^0.0.33 - checksum: 1c2a616a73f1b3435ce04030261bed0e22d4737e14b090bb48e58865da92529c9f2b05b893de650738d55e692d071819b45e1669259b2b354bc3154d27a698c7 - languageName: node - linkType: hard - -"extglob@npm:^2.0.4": - version: 2.0.4 - resolution: "extglob@npm:2.0.4" - dependencies: - array-unique: ^0.3.2 - define-property: ^1.0.0 - expand-brackets: ^2.1.4 - extend-shallow: ^2.0.1 - fragment-cache: ^0.2.1 - regex-not: ^1.0.0 - snapdragon: ^0.8.1 - to-regex: ^3.0.1 - checksum: a41531b8934735b684cef5e8c5a01d0f298d7d384500ceca38793a9ce098125aab04ee73e2d75d5b2901bc5dddd2b64e1b5e3bf19139ea48bac52af4a92f1d00 - languageName: node - linkType: hard - -"extsprintf@npm:1.3.0": - version: 1.3.0 - resolution: "extsprintf@npm:1.3.0" - checksum: cee7a4a1e34cffeeec18559109de92c27517e5641991ec6bab849aa64e3081022903dd53084f2080d0d2530803aa5ee84f1e9de642c365452f9e67be8f958ce2 +"env-paths@npm:^2.2.0": + version: 2.2.1 + resolution: "env-paths@npm:2.2.1" + checksum: 65b5df55a8bab92229ab2b40dad3b387fad24613263d103a97f91c9fe43ceb21965cd3392b1ccb5d77088021e525c4e0481adb309625d0cb94ade1d1fb8dc17e languageName: node linkType: hard -"extsprintf@npm:^1.2.0": - version: 1.4.0 - resolution: "extsprintf@npm:1.4.0" - checksum: 184dc8a413eb4b1ff16bdce797340e7ded4d28511d56a1c9afa5a95bcff6ace154063823eaf0206dbbb0d14059d74f382a15c34b7c0636fa74a7e681295eb67e +"err-code@npm:^2.0.2": + version: 2.0.3 + resolution: "err-code@npm:2.0.3" + checksum: 8b7b1be20d2de12d2255c0bc2ca638b7af5171142693299416e6a9339bd7d88fc8d7707d913d78e0993176005405a236b066b45666b27b797252c771156ace54 languageName: node linkType: hard -"eyes@npm:^0.1.8": - version: 0.1.8 - resolution: "eyes@npm:0.1.8" - checksum: c31703a92bf36ba75ee8d379ee7985c24ee6149f3a6175f44cec7a05b178c38bce9836d3ca48c9acb0329a960ac2c4b2ead4e60cdd4fe6e8c92cad7cd6913687 +"err-code@npm:^3.0.1": + version: 3.0.1 + resolution: "err-code@npm:3.0.1" + checksum: aede1f1d5ebe6d6b30b5e3175e3cc13e67de2e2e1ad99ce4917e957d7b59e8451ed10ee37dbc6493521920a47082c479b9097e5c39438d4aff4cc84438568a5a languageName: node linkType: hard -"fake-merkle-patricia-tree@npm:^1.0.1": - version: 1.0.1 - resolution: "fake-merkle-patricia-tree@npm:1.0.1" +"error-ex@npm:^1.3.1": + version: 1.3.2 + resolution: "error-ex@npm:1.3.2" dependencies: - checkpoint-store: ^1.1.0 - checksum: 8f9fe05bb5beabb31e4fbb8d2cfe83cfb36fd9f6ba78193dea8fab7a679470d45bb04c6f052d4f79da03e81129c5b5bed528902430184e1e11b4959f397019ac + is-arrayish: ^0.2.1 + checksum: c1c2b8b65f9c91b0f9d75f0debaa7ec5b35c266c2cac5de412c1a6de86d4cbae04ae44e510378cb14d032d0645a36925d0186f8bb7367bcc629db256b743a001 languageName: node linkType: hard -"fast-base64-decode@npm:^1.0.0": - version: 1.0.0 - resolution: "fast-base64-decode@npm:1.0.0" - checksum: 4c59eb1775a7f132333f296c5082476fdcc8f58d023c42ed6d378d2e2da4c328c7a71562f271181a725dd17cdaa8f2805346cc330cdbad3b8e4b9751508bd0a3 +"es-abstract@npm:^1.19.0, es-abstract@npm:^1.19.1": + version: 1.19.1 + resolution: "es-abstract@npm:1.19.1" + dependencies: + call-bind: ^1.0.2 + es-to-primitive: ^1.2.1 + function-bind: ^1.1.1 + get-intrinsic: ^1.1.1 + get-symbol-description: ^1.0.0 + has: ^1.0.3 + has-symbols: ^1.0.2 + internal-slot: ^1.0.3 + is-callable: ^1.2.4 + is-negative-zero: ^2.0.1 + is-regex: ^1.1.4 + is-shared-array-buffer: ^1.0.1 + is-string: ^1.0.7 + is-weakref: ^1.0.1 + object-inspect: ^1.11.0 + object-keys: ^1.1.1 + object.assign: ^4.1.2 + string.prototype.trimend: ^1.0.4 + string.prototype.trimstart: ^1.0.4 + unbox-primitive: ^1.0.1 + checksum: b6be8410672c5364db3fb01eb786e30c7b4bb32b4af63d381c08840f4382c4a168e7855cd338bf59d4f1a1a1138f4d748d1fd40ec65aaa071876f9e9fbfed949 languageName: node linkType: hard -"fast-decode-uri-component@npm:^1.0.1": - version: 1.0.1 - resolution: "fast-decode-uri-component@npm:1.0.1" - checksum: 427a48fe0907e76f0e9a2c228e253b4d8a8ab21d130ee9e4bb8339c5ba4086235cf9576831f7b20955a752eae4b525a177ff9d5825dd8d416e7726939194fbee +"es-abstract@npm:^1.19.2, es-abstract@npm:^1.19.5, es-abstract@npm:^1.20.0, es-abstract@npm:^1.20.1": + version: 1.20.4 + resolution: "es-abstract@npm:1.20.4" + dependencies: + call-bind: ^1.0.2 + es-to-primitive: ^1.2.1 + function-bind: ^1.1.1 + function.prototype.name: ^1.1.5 + get-intrinsic: ^1.1.3 + get-symbol-description: ^1.0.0 + has: ^1.0.3 + has-property-descriptors: ^1.0.0 + has-symbols: ^1.0.3 + internal-slot: ^1.0.3 + is-callable: ^1.2.7 + is-negative-zero: ^2.0.2 + is-regex: ^1.1.4 + is-shared-array-buffer: ^1.0.2 + is-string: ^1.0.7 + is-weakref: ^1.0.2 + object-inspect: ^1.12.2 + object-keys: ^1.1.1 + object.assign: ^4.1.4 + regexp.prototype.flags: ^1.4.3 + safe-regex-test: ^1.0.0 + string.prototype.trimend: ^1.0.5 + string.prototype.trimstart: ^1.0.5 + unbox-primitive: ^1.0.2 + checksum: 89297cc785c31aedf961a603d5a07ed16471e435d3a1b6d070b54f157cf48454b95cda2ac55e4b86ff4fe3276e835fcffd2771578e6fa634337da49b26826141 languageName: node linkType: hard -"fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": - version: 3.1.3 - resolution: "fast-deep-equal@npm:3.1.3" - checksum: e21a9d8d84f53493b6aa15efc9cfd53dd5b714a1f23f67fb5dc8f574af80df889b3bce25dc081887c6d25457cce704e636395333abad896ccdec03abaf1f3f9d +"es-abstract@npm:^1.22.1": + version: 1.22.2 + resolution: "es-abstract@npm:1.22.2" + dependencies: + array-buffer-byte-length: ^1.0.0 + arraybuffer.prototype.slice: ^1.0.2 + available-typed-arrays: ^1.0.5 + call-bind: ^1.0.2 + es-set-tostringtag: ^2.0.1 + es-to-primitive: ^1.2.1 + function.prototype.name: ^1.1.6 + get-intrinsic: ^1.2.1 + get-symbol-description: ^1.0.0 + globalthis: ^1.0.3 + gopd: ^1.0.1 + has: ^1.0.3 + has-property-descriptors: ^1.0.0 + has-proto: ^1.0.1 + has-symbols: ^1.0.3 + internal-slot: ^1.0.5 + is-array-buffer: ^3.0.2 + is-callable: ^1.2.7 + is-negative-zero: ^2.0.2 + is-regex: ^1.1.4 + is-shared-array-buffer: ^1.0.2 + is-string: ^1.0.7 + is-typed-array: ^1.1.12 + is-weakref: ^1.0.2 + object-inspect: ^1.12.3 + object-keys: ^1.1.1 + object.assign: ^4.1.4 + regexp.prototype.flags: ^1.5.1 + safe-array-concat: ^1.0.1 + safe-regex-test: ^1.0.0 + string.prototype.trim: ^1.2.8 + string.prototype.trimend: ^1.0.7 + string.prototype.trimstart: ^1.0.7 + typed-array-buffer: ^1.0.0 + typed-array-byte-length: ^1.0.0 + typed-array-byte-offset: ^1.0.0 + typed-array-length: ^1.0.4 + unbox-primitive: ^1.0.2 + which-typed-array: ^1.1.11 + checksum: cc70e592d360d7d729859013dee7a610c6b27ed8630df0547c16b0d16d9fe6505a70ee14d1af08d970fdd132b3f88c9ca7815ce72c9011608abf8ab0e55fc515 languageName: node linkType: hard -"fast-diff@npm:^1.1.2": - version: 1.2.0 - resolution: "fast-diff@npm:1.2.0" - checksum: 1b5306eaa9e826564d9e5ffcd6ebd881eb5f770b3f977fcbf38f05c824e42172b53c79920e8429c54eb742ce15a0caf268b0fdd5b38f6de52234c4a8368131ae +"es-array-method-boxes-properly@npm:^1.0.0": + version: 1.0.0 + resolution: "es-array-method-boxes-properly@npm:1.0.0" + checksum: 2537fcd1cecf187083890bc6f5236d3a26bf39237433587e5bf63392e88faae929dbba78ff0120681a3f6f81c23fe3816122982c160d63b38c95c830b633b826 languageName: node linkType: hard -"fast-fifo@npm:^1.0.0": - version: 1.3.0 - resolution: "fast-fifo@npm:1.3.0" - checksum: edc589b818eede61d0048f399daf67cbc5ef736588669482a20f37269b4808356e54ab89676fd8fa59b26c216c11e5ac57335cc70dca54fbbf692d4acde10de6 +"es-set-tostringtag@npm:^2.0.1": + version: 2.0.1 + resolution: "es-set-tostringtag@npm:2.0.1" + dependencies: + get-intrinsic: ^1.1.3 + has: ^1.0.3 + has-tostringtag: ^1.0.0 + checksum: ec416a12948cefb4b2a5932e62093a7cf36ddc3efd58d6c58ca7ae7064475ace556434b869b0bbeb0c365f1032a8ccd577211101234b69837ad83ad204fff884 languageName: node linkType: hard -"fast-glob@npm:^3.0.3": - version: 3.2.12 - resolution: "fast-glob@npm:3.2.12" +"es-shim-unscopables@npm:^1.0.0": + version: 1.0.0 + resolution: "es-shim-unscopables@npm:1.0.0" dependencies: - "@nodelib/fs.stat": ^2.0.2 - "@nodelib/fs.walk": ^1.2.3 - glob-parent: ^5.1.2 - merge2: ^1.3.0 - micromatch: ^4.0.4 - checksum: 0b1990f6ce831c7e28c4d505edcdaad8e27e88ab9fa65eedadb730438cfc7cde4910d6c975d6b7b8dc8a73da4773702ebcfcd6e3518e73938bb1383badfe01c2 + has: ^1.0.3 + checksum: 83e95cadbb6ee44d3644dfad60dcad7929edbc42c85e66c3e99aefd68a3a5c5665f2686885cddb47dfeabfd77bd5ea5a7060f2092a955a729bbd8834f0d86fa1 languageName: node linkType: hard -"fast-glob@npm:^3.1.1": - version: 3.2.7 - resolution: "fast-glob@npm:3.2.7" +"es-to-primitive@npm:^1.2.1": + version: 1.2.1 + resolution: "es-to-primitive@npm:1.2.1" dependencies: - "@nodelib/fs.stat": ^2.0.2 - "@nodelib/fs.walk": ^1.2.3 - glob-parent: ^5.1.2 - merge2: ^1.3.0 - micromatch: ^4.0.4 - checksum: 2f4708ff112d2b451888129fdd9a0938db88b105b0ddfd043c064e3c4d3e20eed8d7c7615f7565fee660db34ddcf08a2db1bf0ab3c00b87608e4719694642d78 + is-callable: ^1.1.4 + is-date-object: ^1.0.1 + is-symbol: ^1.0.2 + checksum: 4ead6671a2c1402619bdd77f3503991232ca15e17e46222b0a41a5d81aebc8740a77822f5b3c965008e631153e9ef0580540007744521e72de8e33599fca2eed languageName: node linkType: hard -"fast-glob@npm:^3.2.9": - version: 3.3.0 - resolution: "fast-glob@npm:3.3.0" +"es5-ext@npm:^0.10.35, es5-ext@npm:^0.10.50": + version: 0.10.62 + resolution: "es5-ext@npm:0.10.62" dependencies: - "@nodelib/fs.stat": ^2.0.2 - "@nodelib/fs.walk": ^1.2.3 - glob-parent: ^5.1.2 - merge2: ^1.3.0 - micromatch: ^4.0.4 - checksum: 20df62be28eb5426fe8e40e0d05601a63b1daceb7c3d87534afcad91bdcf1e4b1743cf2d5247d6e225b120b46df0b9053a032b2691ba34ee121e033acd81f547 + es6-iterator: ^2.0.3 + es6-symbol: ^3.1.3 + next-tick: ^1.1.0 + checksum: 25f42f6068cfc6e393cf670bc5bba249132c5f5ec2dd0ed6e200e6274aca2fed8e9aec8a31c76031744c78ca283c57f0b41c7e737804c6328c7b8d3fbcba7983 languageName: node linkType: hard -"fast-json-stable-stringify@npm:^2.0.0": - version: 2.1.0 - resolution: "fast-json-stable-stringify@npm:2.1.0" - checksum: b191531e36c607977e5b1c47811158733c34ccb3bfde92c44798929e9b4154884378536d26ad90dfecd32e1ffc09c545d23535ad91b3161a27ddbb8ebe0cbecb +"es6-iterator@npm:^2.0.3": + version: 2.0.3 + resolution: "es6-iterator@npm:2.0.3" + dependencies: + d: 1 + es5-ext: ^0.10.35 + es6-symbol: ^3.1.1 + checksum: 6e48b1c2d962c21dee604b3d9f0bc3889f11ed5a8b33689155a2065d20e3107e2a69cc63a71bd125aeee3a589182f8bbcb5c8a05b6a8f38fa4205671b6d09697 languageName: node linkType: hard -"fast-levenshtein@npm:^2.0.6, fast-levenshtein@npm:~2.0.6": - version: 2.0.6 - resolution: "fast-levenshtein@npm:2.0.6" - checksum: 92cfec0a8dfafd9c7a15fba8f2cc29cd0b62b85f056d99ce448bbcd9f708e18ab2764bda4dd5158364f4145a7c72788538994f0d1787b956ef0d1062b0f7c24c +"es6-promise@npm:^4.0.3, es6-promise@npm:^4.2.8": + version: 4.2.8 + resolution: "es6-promise@npm:4.2.8" + checksum: 95614a88873611cb9165a85d36afa7268af5c03a378b35ca7bda9508e1d4f1f6f19a788d4bc755b3fd37c8ebba40782018e02034564ff24c9d6fa37e959ad57d languageName: node linkType: hard -"fast-levenshtein@npm:^3.0.0": - version: 3.0.0 - resolution: "fast-levenshtein@npm:3.0.0" +"es6-promisify@npm:^5.0.0": + version: 5.0.0 + resolution: "es6-promisify@npm:5.0.0" dependencies: - fastest-levenshtein: ^1.0.7 - checksum: 02732ba6c656797ca7e987c25f3e53718c8fcc39a4bfab46def78eef7a8729eb629632d4a7eca4c27a33e10deabffa9984839557e18a96e91ecf7ccaeedb9890 + es6-promise: ^4.0.3 + checksum: fbed9d791598831413be84a5374eca8c24800ec71a16c1c528c43a98e2dadfb99331483d83ae6094ddb9b87e6f799a15d1553cebf756047e0865c753bc346b92 languageName: node linkType: hard -"fast-querystring@npm:^1.1.1": - version: 1.1.2 - resolution: "fast-querystring@npm:1.1.2" +"es6-symbol@npm:^3.1.1, es6-symbol@npm:^3.1.3": + version: 3.1.3 + resolution: "es6-symbol@npm:3.1.3" dependencies: - fast-decode-uri-component: ^1.0.1 - checksum: 7149f82ee9ac39a9c08c7ffe435b9f6deade76ae5e3675fe1835720513e8c4bc541e666b4b7b1c0c07e08f369dcf4828d00f2bee39889a90a168e1439cf27b0b + d: ^1.0.1 + ext: ^1.1.2 + checksum: cd49722c2a70f011eb02143ef1c8c70658d2660dead6641e160b94619f408b9cf66425515787ffe338affdf0285ad54f4eae30ea5bd510e33f8659ec53bcaa70 languageName: node linkType: hard -"fast-url-parser@npm:^1.1.3": - version: 1.1.3 - resolution: "fast-url-parser@npm:1.1.3" - dependencies: - punycode: ^1.3.2 - checksum: 5043d0c4a8d775ff58504d56c096563c11b113e4cb8a2668c6f824a1cd4fb3812e2fdf76537eb24a7ce4ae7def6bd9747da630c617cf2a4b6ce0c42514e4f21c +"escalade@npm:^3.1.1": + version: 3.1.1 + resolution: "escalade@npm:3.1.1" + checksum: a3e2a99f07acb74b3ad4989c48ca0c3140f69f923e56d0cba0526240ee470b91010f9d39001f2a4a313841d237ede70a729e92125191ba5d21e74b106800b133 languageName: node linkType: hard -"fastest-levenshtein@npm:^1.0.7": - version: 1.0.16 - resolution: "fastest-levenshtein@npm:1.0.16" - checksum: a78d44285c9e2ae2c25f3ef0f8a73f332c1247b7ea7fb4a191e6bb51aa6ee1ef0dfb3ed113616dcdc7023e18e35a8db41f61c8d88988e877cf510df8edafbc71 +"escape-html@npm:~1.0.3": + version: 1.0.3 + resolution: "escape-html@npm:1.0.3" + checksum: 6213ca9ae00d0ab8bccb6d8d4e0a98e76237b2410302cf7df70aaa6591d509a2a37ce8998008cbecae8fc8ffaadf3fb0229535e6a145f3ce0b211d060decbb24 languageName: node linkType: hard -"fastq@npm:^1.6.0": - version: 1.13.0 - resolution: "fastq@npm:1.13.0" - dependencies: - reusify: ^1.0.4 - checksum: 32cf15c29afe622af187d12fc9cd93e160a0cb7c31a3bb6ace86b7dea3b28e7b72acde89c882663f307b2184e14782c6c664fa315973c03626c7d4bff070bb0b +"escape-string-regexp@npm:1.0.5, escape-string-regexp@npm:^1.0.2, escape-string-regexp@npm:^1.0.5": + version: 1.0.5 + resolution: "escape-string-regexp@npm:1.0.5" + checksum: 6092fda75c63b110c706b6a9bfde8a612ad595b628f0bd2147eea1d3406723020810e591effc7db1da91d80a71a737a313567c5abb3813e8d9c71f4aa595b410 languageName: node linkType: hard -"fetch-ponyfill@npm:^4.0.0": - version: 4.1.0 - resolution: "fetch-ponyfill@npm:4.1.0" - dependencies: - node-fetch: ~1.7.1 - checksum: 00c85b661a8314e18cb314640b69d3b6e9635517d54290c8f366ddcb21b506ac8fa5d92f899c0fe21bc2163238130be2cf73ffd9d5a8a41a9866a55c52f57f16 +"escape-string-regexp@npm:4.0.0, escape-string-regexp@npm:^4.0.0": + version: 4.0.0 + resolution: "escape-string-regexp@npm:4.0.0" + checksum: 98b48897d93060f2322108bf29db0feba7dd774be96cd069458d1453347b25ce8682ecc39859d4bca2203cc0ab19c237bcc71755eff49a0f8d90beadeeba5cc5 languageName: node linkType: hard -"figures@npm:^1.3.5": - version: 1.7.0 - resolution: "figures@npm:1.7.0" +"escodegen@npm:1.8.x": + version: 1.8.1 + resolution: "escodegen@npm:1.8.1" dependencies: - escape-string-regexp: ^1.0.5 - object-assign: ^4.1.0 - checksum: d77206deba991a7977f864b8c8edf9b8b43b441be005482db04b0526e36263adbdb22c1c6d2df15a1ad78d12029bd1aa41ccebcb5d425e1f2cf629c6daaa8e10 + esprima: ^2.7.1 + estraverse: ^1.9.1 + esutils: ^2.0.2 + optionator: ^0.8.1 + source-map: ~0.2.0 + dependenciesMeta: + source-map: + optional: true + bin: + escodegen: ./bin/escodegen.js + esgenerate: ./bin/esgenerate.js + checksum: 99f5579dbc309d8f95f8051cce2f85620c073ff1d4f7b58197addee7e81aeb5281dadfbd446a0885b8fb8c0c47ce5c2cdb5f97dbfddccb5126cca5eb9af73992 languageName: node linkType: hard -"figures@npm:^2.0.0": - version: 2.0.0 - resolution: "figures@npm:2.0.0" - dependencies: - escape-string-regexp: ^1.0.5 - checksum: 081beb16ea57d1716f8447c694f637668322398b57017b20929376aaf5def9823b35245b734cdd87e4832dc96e9c6f46274833cada77bfe15e5f980fea1fd21f +"eslint-config-prettier@npm:^8.3.0": + version: 8.3.0 + resolution: "eslint-config-prettier@npm:8.3.0" + peerDependencies: + eslint: ">=7.0.0" + bin: + eslint-config-prettier: bin/cli.js + checksum: df4cea3032671995bb5ab07e016169072f7fa59f44a53251664d9ca60951b66cdc872683b5c6a3729c91497c11490ca44a79654b395dd6756beb0c3903a37196 languageName: node linkType: hard -"file-entry-cache@npm:^5.0.1": - version: 5.0.1 - resolution: "file-entry-cache@npm:5.0.1" - dependencies: - flat-cache: ^2.0.1 - checksum: 9014b17766815d59b8b789633aed005242ef857348c09be558bd85b4a24e16b0ad1e0e5229ccea7a2109f74ef1b3db1a559b58afe12b884f09019308711376fd +"eslint-config-standard-kit@npm:0.15.1": + version: 0.15.1 + resolution: "eslint-config-standard-kit@npm:0.15.1" + checksum: da4a34544f0ea0325d0340c78cb625e785aa4c7121fa25805c11290fb62f7a3573f61b783957245050b6c0901e30618c508d2df4984a1ba120c0fe93f3773131 languageName: node linkType: hard -"file-entry-cache@npm:^6.0.1": - version: 6.0.1 - resolution: "file-entry-cache@npm:6.0.1" +"eslint-import-resolver-node@npm:^0.3.6": + version: 0.3.6 + resolution: "eslint-import-resolver-node@npm:0.3.6" dependencies: - flat-cache: ^3.0.4 - checksum: f49701feaa6314c8127c3c2f6173cfefff17612f5ed2daaafc6da13b5c91fd43e3b2a58fd0d63f9f94478a501b167615931e7200e31485e320f74a33885a9c74 + debug: ^3.2.7 + resolve: ^1.20.0 + checksum: 6266733af1e112970e855a5bcc2d2058fb5ae16ad2a6d400705a86b29552b36131ffc5581b744c23d550de844206fb55e9193691619ee4dbf225c4bde526b1c8 languageName: node linkType: hard -"file-uri-to-path@npm:1.0.0": - version: 1.0.0 - resolution: "file-uri-to-path@npm:1.0.0" - checksum: b648580bdd893a008c92c7ecc96c3ee57a5e7b6c4c18a9a09b44fb5d36d79146f8e442578bc0e173dc027adf3987e254ba1dfd6e3ec998b7c282873010502144 +"eslint-module-utils@npm:^2.7.0": + version: 2.7.1 + resolution: "eslint-module-utils@npm:2.7.1" + dependencies: + debug: ^3.2.7 + find-up: ^2.1.0 + pkg-dir: ^2.0.0 + checksum: c30dfa125aafe65e5f6a30a31c26932106fcf09934a2f47d7f8a393ed9106da7b07416f2337b55c85f9db0175c873ee0827be5429a24ec381b49940f342b9ac3 languageName: node linkType: hard -"filelist@npm:^1.0.4": - version: 1.0.4 - resolution: "filelist@npm:1.0.4" +"eslint-plugin-es@npm:^3.0.0": + version: 3.0.1 + resolution: "eslint-plugin-es@npm:3.0.1" dependencies: - minimatch: ^5.0.1 - checksum: a303573b0821e17f2d5e9783688ab6fbfce5d52aaac842790ae85e704a6f5e4e3538660a63183d6453834dedf1e0f19a9dadcebfa3e926c72397694ea11f5160 + eslint-utils: ^2.0.0 + regexpp: ^3.0.0 + peerDependencies: + eslint: ">=4.19.1" + checksum: e57592c52301ee8ddc296ae44216df007f3a870bcb3be8d1fbdb909a1d3a3efe3fa3785de02066f9eba1d6466b722d3eb3cc3f8b75b3cf6a1cbded31ac6298e4 languageName: node linkType: hard -"fill-range@npm:^4.0.0": - version: 4.0.0 - resolution: "fill-range@npm:4.0.0" +"eslint-plugin-import@npm:^2.25.2": + version: 2.25.2 + resolution: "eslint-plugin-import@npm:2.25.2" dependencies: - extend-shallow: ^2.0.1 - is-number: ^3.0.0 - repeat-string: ^1.6.1 - to-regex-range: ^2.1.0 - checksum: dbb5102467786ab42bc7a3ec7380ae5d6bfd1b5177b2216de89e4a541193f8ba599a6db84651bd2c58c8921db41b8cc3d699ea83b477342d3ce404020f73c298 + array-includes: ^3.1.4 + array.prototype.flat: ^1.2.5 + debug: ^2.6.9 + doctrine: ^2.1.0 + eslint-import-resolver-node: ^0.3.6 + eslint-module-utils: ^2.7.0 + has: ^1.0.3 + is-core-module: ^2.7.0 + is-glob: ^4.0.3 + minimatch: ^3.0.4 + object.values: ^1.1.5 + resolve: ^1.20.0 + tsconfig-paths: ^3.11.0 + peerDependencies: + eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 + checksum: 4ca36e37faf72fb1ed25361ea8a6abbcc9daa65f3a9ac1dc0a660029000456e8c8b98a87b8cc2316541b13c6e5915df41d2dc4a1d7fe0729d9b72b9a3bd5b909 languageName: node linkType: hard -"fill-range@npm:^7.0.1": - version: 7.0.1 - resolution: "fill-range@npm:7.0.1" +"eslint-plugin-node@npm:^11.1.0": + version: 11.1.0 + resolution: "eslint-plugin-node@npm:11.1.0" dependencies: - to-regex-range: ^5.0.1 - checksum: cc283f4e65b504259e64fd969bcf4def4eb08d85565e906b7d36516e87819db52029a76b6363d0f02d0d532f0033c9603b9e2d943d56ee3b0d4f7ad3328ff917 + eslint-plugin-es: ^3.0.0 + eslint-utils: ^2.0.0 + ignore: ^5.1.1 + minimatch: ^3.0.4 + resolve: ^1.10.1 + semver: ^6.1.0 + peerDependencies: + eslint: ">=5.16.0" + checksum: 5804c4f8a6e721f183ef31d46fbe3b4e1265832f352810060e0502aeac7de034df83352fc88643b19641bb2163f2587f1bd4119aff0fd21e8d98c57c450e013b languageName: node linkType: hard -"finalhandler@npm:1.2.0": - version: 1.2.0 - resolution: "finalhandler@npm:1.2.0" +"eslint-plugin-prettier@npm:^5.0.0": + version: 5.5.5 + resolution: "eslint-plugin-prettier@npm:5.5.5" dependencies: - debug: 2.6.9 - encodeurl: ~1.0.2 - escape-html: ~1.0.3 - on-finished: 2.4.1 - parseurl: ~1.3.3 - statuses: 2.0.1 - unpipe: ~1.0.0 - checksum: 92effbfd32e22a7dff2994acedbd9bcc3aa646a3e919ea6a53238090e87097f8ef07cced90aa2cc421abdf993aefbdd5b00104d55c7c5479a8d00ed105b45716 + prettier-linter-helpers: ^1.0.1 + synckit: ^0.11.12 + peerDependencies: + "@types/eslint": ">=8.0.0" + eslint: ">=8.0.0" + eslint-config-prettier: ">= 7.0.0 <10.0.0 || >=10.1.0" + prettier: ">=3.0.0" + peerDependenciesMeta: + "@types/eslint": + optional: true + eslint-config-prettier: + optional: true + checksum: 49b1c25d75ded255a8707d5f06288ae86e8ab4f8e273d4aabdabf73cd0903848916d5a3598ba8be82f2c8dd06769c5e6c172503b3b9cfb2636b6fc23b9c024fb languageName: node linkType: hard -"find-replace@npm:^1.0.3": - version: 1.0.3 - resolution: "find-replace@npm:1.0.3" - dependencies: - array-back: ^1.0.4 - test-value: ^2.1.0 - checksum: fd95f44e59bd54ea1c0169480952b339a4642cd62d81236fef7f87146d3bc00a042b17d81f896712e8542e01fe5c84e82ac37b6b77b4e3422abbcf7c13bbacfd +"eslint-plugin-simple-import-sort@npm:^7.0.0": + version: 7.0.0 + resolution: "eslint-plugin-simple-import-sort@npm:7.0.0" + peerDependencies: + eslint: ">=5.0.0" + checksum: 6aacb7179c213cd2081950630368d1f3b1dcb4f5674d8b989fe7839e7b317ee521d74761676e8b1a7cab49f20405dbcc9aac05358ae804e6bcba6cbf1daccb3d languageName: node linkType: hard -"find-replace@npm:^3.0.0": - version: 3.0.0 - resolution: "find-replace@npm:3.0.0" +"eslint-plugin-unused-imports@npm:^3.0.0": + version: 3.2.0 + resolution: "eslint-plugin-unused-imports@npm:3.2.0" dependencies: - array-back: ^3.0.1 - checksum: 6b04bcfd79027f5b84aa1dfe100e3295da989bdac4b4de6b277f4d063e78f5c9e92ebc8a1fec6dd3b448c924ba404ee051cc759e14a3ee3e825fa1361025df08 + eslint-rule-composer: ^0.3.0 + peerDependencies: + "@typescript-eslint/eslint-plugin": 6 - 7 + eslint: 8 + peerDependenciesMeta: + "@typescript-eslint/eslint-plugin": + optional: true + checksum: e85ae4f3af489294ef5e0969ab904fa87f9fa7c959ca0804f30845438db4aeb0428ddad7ab06a70608e93121626799977241b442fdf126a4d0667be57390c3d6 languageName: node linkType: hard -"find-up@npm:3.0.0, find-up@npm:^3.0.0": - version: 3.0.0 - resolution: "find-up@npm:3.0.0" - dependencies: - locate-path: ^3.0.0 - checksum: 38eba3fe7a66e4bc7f0f5a1366dc25508b7cfc349f852640e3678d26ad9a6d7e2c43eff0a472287de4a9753ef58f066a0ea892a256fa3636ad51b3fe1e17fae9 +"eslint-rule-composer@npm:^0.3.0": + version: 0.3.0 + resolution: "eslint-rule-composer@npm:0.3.0" + checksum: c2f57cded8d1c8f82483e0ce28861214347e24fd79fd4144667974cd334d718f4ba05080aaef2399e3bbe36f7d6632865110227e6b176ed6daa2d676df9281b1 languageName: node linkType: hard -"find-up@npm:5.0.0": - version: 5.0.0 - resolution: "find-up@npm:5.0.0" +"eslint-scope@npm:^4.0.3": + version: 4.0.3 + resolution: "eslint-scope@npm:4.0.3" dependencies: - locate-path: ^6.0.0 - path-exists: ^4.0.0 - checksum: 07955e357348f34660bde7920783204ff5a26ac2cafcaa28bace494027158a97b9f56faaf2d89a6106211a8174db650dd9f503f9c0d526b1202d5554a00b9095 + esrecurse: ^4.1.0 + estraverse: ^4.1.1 + checksum: c5f835f681884469991fe58d76a554688d9c9e50811299ccd4a8f79993a039f5bcb0ee6e8de2b0017d97c794b5832ef3b21c9aac66228e3aa0f7a0485bcfb65b languageName: node linkType: hard -"find-up@npm:^1.0.0": - version: 1.1.2 - resolution: "find-up@npm:1.1.2" +"eslint-scope@npm:^7.2.2": + version: 7.2.2 + resolution: "eslint-scope@npm:7.2.2" dependencies: - path-exists: ^2.0.0 - pinkie-promise: ^2.0.0 - checksum: a2cb9f4c9f06ee3a1e92ed71d5aed41ac8ae30aefa568132f6c556fac7678a5035126153b59eaec68da78ac409eef02503b2b059706bdbf232668d7245e3240a + esrecurse: ^4.3.0 + estraverse: ^5.2.0 + checksum: ec97dbf5fb04b94e8f4c5a91a7f0a6dd3c55e46bfc7bbcd0e3138c3a76977570e02ed89a1810c778dcd72072ff0e9621ba1379b4babe53921d71e2e4486fda3e languageName: node linkType: hard -"find-up@npm:^2.1.0": - version: 2.1.0 - resolution: "find-up@npm:2.1.0" +"eslint-utils@npm:^1.3.1": + version: 1.4.3 + resolution: "eslint-utils@npm:1.4.3" dependencies: - locate-path: ^2.0.0 - checksum: 43284fe4da09f89011f08e3c32cd38401e786b19226ea440b75386c1b12a4cb738c94969808d53a84f564ede22f732c8409e3cfc3f7fb5b5c32378ad0bbf28bd + eslint-visitor-keys: ^1.1.0 + checksum: a20630e686034107138272f245c460f6d77705d1f4bb0628c1a1faf59fc800f441188916b3ec3b957394dc405aa200a3017dfa2b0fff0976e307a4e645a18d1e languageName: node linkType: hard -"find-yarn-workspace-root@npm:^1.2.1": - version: 1.2.1 - resolution: "find-yarn-workspace-root@npm:1.2.1" +"eslint-utils@npm:^2.0.0": + version: 2.1.0 + resolution: "eslint-utils@npm:2.1.0" dependencies: - fs-extra: ^4.0.3 - micromatch: ^3.1.4 - checksum: a8f4565fb1ead6122acc0d324fa3257c20f7b0c91b7b266dab9eee7251fb5558fcff5b35dbfd301bfd1cbb91c1cdd1799b28ffa5b9a92efd8c7ded3663652bbe + eslint-visitor-keys: ^1.1.0 + checksum: 27500938f348da42100d9e6ad03ae29b3de19ba757ae1a7f4a087bdcf83ac60949bbb54286492ca61fac1f5f3ac8692dd21537ce6214240bf95ad0122f24d71d languageName: node linkType: hard -"find-yarn-workspace-root@npm:^2.0.0": - version: 2.0.0 - resolution: "find-yarn-workspace-root@npm:2.0.0" - dependencies: - micromatch: ^4.0.2 - checksum: fa5ca8f9d08fe7a54ce7c0a5931ff9b7e36f9ee7b9475fb13752bcea80ec6b5f180fa5102d60b376d5526ce924ea3fc6b19301262efa0a5d248dd710f3644242 +"eslint-visitor-keys@npm:^1.0.0, eslint-visitor-keys@npm:^1.1.0": + version: 1.3.0 + resolution: "eslint-visitor-keys@npm:1.3.0" + checksum: 37a19b712f42f4c9027e8ba98c2b06031c17e0c0a4c696cd429bd9ee04eb43889c446f2cd545e1ff51bef9593fcec94ecd2c2ef89129fcbbf3adadbef520376a languageName: node linkType: hard -"flat-cache@npm:^2.0.1": - version: 2.0.1 - resolution: "flat-cache@npm:2.0.1" - dependencies: - flatted: ^2.0.0 - rimraf: 2.6.3 - write: 1.0.3 - checksum: 0f5e66467658039e6fcaaccb363b28f43906ba72fab7ff2a4f6fcd5b4899679e13ca46d9fc6cc48b68ac925ae93137106d4aaeb79874c13f21f87a361705f1b1 +"eslint-visitor-keys@npm:^3.4.1, eslint-visitor-keys@npm:^3.4.3": + version: 3.4.3 + resolution: "eslint-visitor-keys@npm:3.4.3" + checksum: 36e9ef87fca698b6fd7ca5ca35d7b2b6eeaaf106572e2f7fd31c12d3bfdaccdb587bba6d3621067e5aece31c8c3a348b93922ab8f7b2cbc6aaab5e1d89040c60 languageName: node linkType: hard -"flat-cache@npm:^3.0.4": - version: 3.0.4 - resolution: "flat-cache@npm:3.0.4" +"eslint@npm:^5.6.0": + version: 5.16.0 + resolution: "eslint@npm:5.16.0" dependencies: - flatted: ^3.1.0 - rimraf: ^3.0.2 - checksum: 4fdd10ecbcbf7d520f9040dd1340eb5dfe951e6f0ecf2252edeec03ee68d989ec8b9a20f4434270e71bcfd57800dc09b3344fca3966b2eb8f613072c7d9a2365 + "@babel/code-frame": ^7.0.0 + ajv: ^6.9.1 + chalk: ^2.1.0 + cross-spawn: ^6.0.5 + debug: ^4.0.1 + doctrine: ^3.0.0 + eslint-scope: ^4.0.3 + eslint-utils: ^1.3.1 + eslint-visitor-keys: ^1.0.0 + espree: ^5.0.1 + esquery: ^1.0.1 + esutils: ^2.0.2 + file-entry-cache: ^5.0.1 + functional-red-black-tree: ^1.0.1 + glob: ^7.1.2 + globals: ^11.7.0 + ignore: ^4.0.6 + import-fresh: ^3.0.0 + imurmurhash: ^0.1.4 + inquirer: ^6.2.2 + js-yaml: ^3.13.0 + json-stable-stringify-without-jsonify: ^1.0.1 + levn: ^0.3.0 + lodash: ^4.17.11 + minimatch: ^3.0.4 + mkdirp: ^0.5.1 + natural-compare: ^1.4.0 + optionator: ^0.8.2 + path-is-inside: ^1.0.2 + progress: ^2.0.0 + regexpp: ^2.0.1 + semver: ^5.5.1 + strip-ansi: ^4.0.0 + strip-json-comments: ^2.0.1 + table: ^5.2.3 + text-table: ^0.2.0 + bin: + eslint: ./bin/eslint.js + checksum: 53c6b9420992df95f986dc031f76949edbea14bdeed4e40d8cda8970fbf0fc013c6d91b98f469b6477753e50c9af133c1a768e421a1c160ec2cac7a246e05494 languageName: node linkType: hard -"flat@npm:^4.1.0": - version: 4.1.1 - resolution: "flat@npm:4.1.1" +"eslint@npm:^8.56.0": + version: 8.57.1 + resolution: "eslint@npm:8.57.1" dependencies: - is-buffer: ~2.0.3 + "@eslint-community/eslint-utils": ^4.2.0 + "@eslint-community/regexpp": ^4.6.1 + "@eslint/eslintrc": ^2.1.4 + "@eslint/js": 8.57.1 + "@humanwhocodes/config-array": ^0.13.0 + "@humanwhocodes/module-importer": ^1.0.1 + "@nodelib/fs.walk": ^1.2.8 + "@ungap/structured-clone": ^1.2.0 + ajv: ^6.12.4 + chalk: ^4.0.0 + cross-spawn: ^7.0.2 + debug: ^4.3.2 + doctrine: ^3.0.0 + escape-string-regexp: ^4.0.0 + eslint-scope: ^7.2.2 + eslint-visitor-keys: ^3.4.3 + espree: ^9.6.1 + esquery: ^1.4.2 + esutils: ^2.0.2 + fast-deep-equal: ^3.1.3 + file-entry-cache: ^6.0.1 + find-up: ^5.0.0 + glob-parent: ^6.0.2 + globals: ^13.19.0 + graphemer: ^1.4.0 + ignore: ^5.2.0 + imurmurhash: ^0.1.4 + is-glob: ^4.0.0 + is-path-inside: ^3.0.3 + js-yaml: ^4.1.0 + json-stable-stringify-without-jsonify: ^1.0.1 + levn: ^0.4.1 + lodash.merge: ^4.6.2 + minimatch: ^3.1.2 + natural-compare: ^1.4.0 + optionator: ^0.9.3 + strip-ansi: ^6.0.1 + text-table: ^0.2.0 bin: - flat: cli.js - checksum: 398be12185eb0f3c59797c3670a8c35d07020b673363175676afbaf53d6b213660e060488554cf82c25504986e1a6059bdbcc5d562e87ca3e972e8a33148e3ae + eslint: bin/eslint.js + checksum: e2489bb7f86dd2011967759a09164e65744ef7688c310bc990612fc26953f34cc391872807486b15c06833bdff737726a23e9b4cdba5de144c311377dc41d91b languageName: node linkType: hard -"flat@npm:^5.0.2": - version: 5.0.2 - resolution: "flat@npm:5.0.2" - bin: - flat: cli.js - checksum: 12a1536ac746db74881316a181499a78ef953632ddd28050b7a3a43c62ef5462e3357c8c29d76072bb635f147f7a9a1f0c02efef6b4be28f8db62ceb3d5c7f5d +"espree@npm:^5.0.1": + version: 5.0.1 + resolution: "espree@npm:5.0.1" + dependencies: + acorn: ^6.0.7 + acorn-jsx: ^5.0.0 + eslint-visitor-keys: ^1.0.0 + checksum: a091aac2bddf872484b0a7e779e3a1ffab32d1c55a6c4f99e483613a0149443531272c191eda1c7c827e32a9e10f6ce7ea6b131c7b3f4e12471fe618ebbc5b7e languageName: node linkType: hard -"flatted@npm:^2.0.0": - version: 2.0.2 - resolution: "flatted@npm:2.0.2" - checksum: 473c754db7a529e125a22057098f1a4c905ba17b8cc269c3acf77352f0ffa6304c851eb75f6a1845f74461f560e635129ca6b0b8a78fb253c65cea4de3d776f2 +"espree@npm:^9.6.0, espree@npm:^9.6.1": + version: 9.6.1 + resolution: "espree@npm:9.6.1" + dependencies: + acorn: ^8.9.0 + acorn-jsx: ^5.3.2 + eslint-visitor-keys: ^3.4.1 + checksum: eb8c149c7a2a77b3f33a5af80c10875c3abd65450f60b8af6db1bfcfa8f101e21c1e56a561c6dc13b848e18148d43469e7cd208506238554fb5395a9ea5a1ab9 languageName: node linkType: hard -"flatted@npm:^3.1.0": - version: 3.2.2 - resolution: "flatted@npm:3.2.2" - checksum: 9d5e03fd9309b9103f345cf6d0cef4fa46201baa053b0ca3d57fa489449b0bee687b7355407898f630afbb1a1286d2a6658e7e77dea3b85c3cd6c6ce2894a5c3 +"esprima@npm:2.7.x, esprima@npm:^2.7.1": + version: 2.7.3 + resolution: "esprima@npm:2.7.3" + bin: + esparse: ./bin/esparse.js + esvalidate: ./bin/esvalidate.js + checksum: 55584508dca0551885e62c3369bc4a783bd948b43e2f034f05c2a37f3ca398db99f072ab228234e9cab09af8dc8c65d6ca7de3a975f2a296b34d1a3aba7e89f1 languageName: node linkType: hard -"flow-stoplight@npm:^1.0.0": - version: 1.0.0 - resolution: "flow-stoplight@npm:1.0.0" - checksum: 2f1f34629e724afe7de7b6cb7b5f9ef1b37fa5a4b8a10e24b9c1043872777c41f4c7e09994ecfd5bc70138a04966c3153c4e15187a24771f5d5151a325a96a2e +"esprima@npm:^4.0.0, esprima@npm:~4.0.0": + version: 4.0.1 + resolution: "esprima@npm:4.0.1" + bin: + esparse: ./bin/esparse.js + esvalidate: ./bin/esvalidate.js + checksum: b45bc805a613dbea2835278c306b91aff6173c8d034223fa81498c77dcbce3b2931bf6006db816f62eacd9fd4ea975dfd85a5b7f3c6402cfd050d4ca3c13a628 languageName: node linkType: hard -"fmix@npm:^0.1.0": - version: 0.1.0 - resolution: "fmix@npm:0.1.0" +"esquery@npm:^1.0.1": + version: 1.4.0 + resolution: "esquery@npm:1.4.0" dependencies: - imul: ^1.0.0 - checksum: c465344d4f169eaf10d45c33949a1e7a633f09dba2ac7063ce8ae8be743df5979d708f7f24900163589f047f5194ac5fc2476177ce31175e8805adfa7b8fb7a4 + estraverse: ^5.1.0 + checksum: a0807e17abd7fbe5fbd4fab673038d6d8a50675cdae6b04fbaa520c34581be0c5fa24582990e8acd8854f671dd291c78bb2efb9e0ed5b62f33bac4f9cf820210 languageName: node linkType: hard -"follow-redirects@npm:^1.12.1, follow-redirects@npm:^1.14.8, follow-redirects@npm:^1.15.0": - version: 1.15.2 - resolution: "follow-redirects@npm:1.15.2" - peerDependenciesMeta: - debug: - optional: true - checksum: faa66059b66358ba65c234c2f2a37fcec029dc22775f35d9ad6abac56003268baf41e55f9ee645957b32c7d9f62baf1f0b906e68267276f54ec4b4c597c2b190 +"esquery@npm:^1.4.2": + version: 1.7.0 + resolution: "esquery@npm:1.7.0" + dependencies: + estraverse: ^5.1.0 + checksum: 3239792b68cf39fe18966d0ca01549bb15556734f0144308fd213739b0f153671ae916013fce0bca032044a4dbcda98b43c1c667f20c20a54dec3597ac0d7c27 languageName: node linkType: hard -"follow-redirects@npm:^1.14.0": - version: 1.14.4 - resolution: "follow-redirects@npm:1.14.4" - peerDependenciesMeta: - debug: - optional: true - checksum: d4ce74cf5c6f363168b97e706b914eb9ffb6bf4d4c6d8f8330b93088d9b90e566611ddbcf0e42c8ed5fd17598dfeda1d19230d3e9d6d6c6b4d1c10ec3a0b99be +"esrecurse@npm:^4.1.0, esrecurse@npm:^4.3.0": + version: 4.3.0 + resolution: "esrecurse@npm:4.3.0" + dependencies: + estraverse: ^5.2.0 + checksum: ebc17b1a33c51cef46fdc28b958994b1dc43cd2e86237515cbc3b4e5d2be6a811b2315d0a1a4d9d340b6d2308b15322f5c8291059521cc5f4802f65e7ec32837 languageName: node linkType: hard -"follow-redirects@npm:^1.15.6": - version: 1.15.9 - resolution: "follow-redirects@npm:1.15.9" - peerDependenciesMeta: - debug: - optional: true - checksum: 859e2bacc7a54506f2bf9aacb10d165df78c8c1b0ceb8023f966621b233717dab56e8d08baadc3ad3b9db58af290413d585c999694b7c146aaf2616340c3d2a6 +"estraverse@npm:^1.9.1": + version: 1.9.3 + resolution: "estraverse@npm:1.9.3" + checksum: 78fa96317500e7783d48297dbd4c7f8735ddeb970be2981b485639ffa77578d05b8f781332622e436f2e9e533f32923c62c2e6463291e577ceeaf2776ac5e4b5 languageName: node linkType: hard -"for-each@npm:^0.3.3, for-each@npm:~0.3.3": - version: 0.3.3 - resolution: "for-each@npm:0.3.3" - dependencies: - is-callable: ^1.1.3 - checksum: 6c48ff2bc63362319c65e2edca4a8e1e3483a2fabc72fbe7feaf8c73db94fc7861bd53bc02c8a66a0c1dd709da6b04eec42e0abdd6b40ce47305ae92a25e5d28 +"estraverse@npm:^4.1.1": + version: 4.3.0 + resolution: "estraverse@npm:4.3.0" + checksum: a6299491f9940bb246124a8d44b7b7a413a8336f5436f9837aaa9330209bd9ee8af7e91a654a3545aee9c54b3308e78ee360cef1d777d37cfef77d2fa33b5827 languageName: node linkType: hard -"for-in@npm:^1.0.2": - version: 1.0.2 - resolution: "for-in@npm:1.0.2" - checksum: 09f4ae93ce785d253ac963d94c7f3432d89398bf25ac7a24ed034ca393bf74380bdeccc40e0f2d721a895e54211b07c8fad7132e8157827f6f7f059b70b4043d +"estraverse@npm:^5.1.0, estraverse@npm:^5.2.0": + version: 5.2.0 + resolution: "estraverse@npm:5.2.0" + checksum: ec11b70d946bf5d7f76f91db38ef6f08109ac1b36cda293a26e678e58df4719f57f67b9ec87042afdd1f0267cee91865be3aa48d2161765a93defab5431be7b8 languageName: node linkType: hard -"forever-agent@npm:~0.6.1": - version: 0.6.1 - resolution: "forever-agent@npm:0.6.1" - checksum: 766ae6e220f5fe23676bb4c6a99387cec5b7b62ceb99e10923376e27bfea72f3c3aeec2ba5f45f3f7ba65d6616965aa7c20b15002b6860833bb6e394dea546a8 +"esutils@npm:^2.0.2": + version: 2.0.3 + resolution: "esutils@npm:2.0.3" + checksum: 22b5b08f74737379a840b8ed2036a5fb35826c709ab000683b092d9054e5c2a82c27818f12604bfc2a9a76b90b6834ef081edbc1c7ae30d1627012e067c6ec87 languageName: node linkType: hard -"form-data-encoder@npm:1.7.1": - version: 1.7.1 - resolution: "form-data-encoder@npm:1.7.1" - checksum: a2a360d5588a70d323c12a140c3db23a503a38f0a5d141af1efad579dde9f9fff2e49e5f31f378cb4631518c1ab4a826452c92f0d2869e954b6b2d77b05613e1 +"etag@npm:~1.8.1": + version: 1.8.1 + resolution: "etag@npm:1.8.1" + checksum: 571aeb3dbe0f2bbd4e4fadbdb44f325fc75335cd5f6f6b6a091e6a06a9f25ed5392f0863c5442acb0646787446e816f13cbfc6edce5b07658541dff573cab1ff languageName: node linkType: hard -"form-data@npm:^2.2.0": - version: 2.5.1 - resolution: "form-data@npm:2.5.1" +"eth-ens-namehash@npm:2.0.8": + version: 2.0.8 + resolution: "eth-ens-namehash@npm:2.0.8" dependencies: - asynckit: ^0.4.0 - combined-stream: ^1.0.6 - mime-types: ^2.1.12 - checksum: 5134ada56cc246b293a1ac7678dba6830000603a3979cf83ff7b2f21f2e3725202237cfb89e32bcb38a1d35727efbd3c3a22e65b42321e8ade8eec01ce755d08 + idna-uts46-hx: ^2.3.1 + js-sha3: ^0.5.7 + checksum: 40ce4aeedaa4e7eb4485c8d8857457ecc46a4652396981d21b7e3a5f922d5beff63c71cb4b283c935293e530eba50b329d9248be3c433949c6bc40c850c202a3 languageName: node linkType: hard -"form-data@npm:^3.0.0": - version: 3.0.1 - resolution: "form-data@npm:3.0.1" +"eth-gas-reporter@npm:^0.2.25": + version: 0.2.25 + resolution: "eth-gas-reporter@npm:0.2.25" dependencies: - asynckit: ^0.4.0 - combined-stream: ^1.0.8 - mime-types: ^2.1.12 - checksum: b019e8d35c8afc14a2bd8a7a92fa4f525a4726b6d5a9740e8d2623c30e308fbb58dc8469f90415a856698933c8479b01646a9dff33c87cc4e76d72aedbbf860d + "@ethersproject/abi": ^5.0.0-beta.146 + "@solidity-parser/parser": ^0.14.0 + cli-table3: ^0.5.0 + colors: 1.4.0 + ethereum-cryptography: ^1.0.3 + ethers: ^4.0.40 + fs-readdir-recursive: ^1.1.0 + lodash: ^4.17.14 + markdown-table: ^1.1.3 + mocha: ^7.1.1 + req-cwd: ^2.0.0 + request: ^2.88.0 + request-promise-native: ^1.0.5 + sha1: ^1.1.1 + sync-request: ^6.0.0 + peerDependencies: + "@codechecks/client": ^0.1.0 + peerDependenciesMeta: + "@codechecks/client": + optional: true + checksum: 3bfa81e554b069bb817f2a073a601a0429e6b582c56ad99db0727dc2a102ab00fc27888820b8a042a194a8fb7d40954d10cd7b011ede6b8170285d2d5a88666c languageName: node linkType: hard -"form-data@npm:^4.0.0": - version: 4.0.0 - resolution: "form-data@npm:4.0.0" +"eth-lib@npm:0.2.8": + version: 0.2.8 + resolution: "eth-lib@npm:0.2.8" dependencies: - asynckit: ^0.4.0 - combined-stream: ^1.0.8 - mime-types: ^2.1.12 - checksum: 01135bf8675f9d5c61ff18e2e2932f719ca4de964e3be90ef4c36aacfc7b9cb2fceb5eca0b7e0190e3383fe51c5b37f4cb80b62ca06a99aaabfcfd6ac7c9328c + bn.js: ^4.11.6 + elliptic: ^6.4.0 + xhr-request-promise: ^0.1.2 + checksum: be7efb0b08a78e20d12d2892363ecbbc557a367573ac82fc26a549a77a1b13c7747e6eadbb88026634828fcf9278884b555035787b575b1cab5e6958faad0fad languageName: node linkType: hard -"form-data@npm:~2.3.2": - version: 2.3.3 - resolution: "form-data@npm:2.3.3" +"eth-lib@npm:^0.1.26": + version: 0.1.29 + resolution: "eth-lib@npm:0.1.29" dependencies: - asynckit: ^0.4.0 - combined-stream: ^1.0.6 - mime-types: ^2.1.12 - checksum: 10c1780fa13dbe1ff3100114c2ce1f9307f8be10b14bf16e103815356ff567b6be39d70fc4a40f8990b9660012dc24b0f5e1dde1b6426166eb23a445ba068ca3 + bn.js: ^4.11.6 + elliptic: ^6.4.0 + nano-json-stream-parser: ^0.1.2 + servify: ^0.1.12 + ws: ^3.0.0 + xhr-request-promise: ^0.1.2 + checksum: d1494fc0af372d46d1c9e7506cfbfa81b9073d98081cf4cbe518932f88bee40cf46a764590f1f8aba03d4a534fa2b1cd794fa2a4f235f656d82b8ab185b5cb9d languageName: node linkType: hard -"forwarded@npm:0.2.0": - version: 0.2.0 - resolution: "forwarded@npm:0.2.0" - checksum: fd27e2394d8887ebd16a66ffc889dc983fbbd797d5d3f01087c020283c0f019a7d05ee85669383d8e0d216b116d720fc0cef2f6e9b7eb9f4c90c6e0bc7fd28e6 +"eth-sig-util@npm:^3.0.1": + version: 3.0.1 + resolution: "eth-sig-util@npm:3.0.1" + dependencies: + ethereumjs-abi: ^0.6.8 + ethereumjs-util: ^5.1.1 + tweetnacl: ^1.0.3 + tweetnacl-util: ^0.15.0 + checksum: 614bf7011b30f78c3532f53e3f80919fe5502b0fa7a3656e6e7dae56d26bc9f559c5b6480c2bcc66d63cd9f72b489732df3b7f1daa0ac9a1fe3b6878347ab4c6 languageName: node linkType: hard -"fp-ts@npm:1.19.3": - version: 1.19.3 - resolution: "fp-ts@npm:1.19.3" - checksum: eb0d4766ad561e9c5c01bfdd3d0ae589af135556921c733d26cf5289aad9f400110defdd93e6ac1d71f626697bb44d9d95ed2879c53dfd868f7cac3cf5c5553c +"ethereum-bloom-filters@npm:^1.0.6": + version: 1.0.10 + resolution: "ethereum-bloom-filters@npm:1.0.10" + dependencies: + js-sha3: ^0.8.0 + checksum: 4019cc6f9274ae271a52959194a72f6e9b013366f168f922dc3b349319faf7426bf1010125ee0676b4f75714fe4a440edd4e7e62342c121a046409f4cd4c0af9 languageName: node linkType: hard -"fp-ts@npm:^1.0.0": - version: 1.19.5 - resolution: "fp-ts@npm:1.19.5" - checksum: 67d2d9c3855d211ca2592b1ef805f98b618157e7681791a776d9d0f7f3e52fcca2122ebf5bc215908c9099fad69756d40e37210cf46cb4075dae1b61efe69e40 +"ethereum-cryptography@npm:^0.1.3": + version: 0.1.3 + resolution: "ethereum-cryptography@npm:0.1.3" + dependencies: + "@types/pbkdf2": ^3.0.0 + "@types/secp256k1": ^4.0.1 + blakejs: ^1.1.0 + browserify-aes: ^1.2.0 + bs58check: ^2.1.2 + create-hash: ^1.2.0 + create-hmac: ^1.1.7 + hash.js: ^1.1.7 + keccak: ^3.0.0 + pbkdf2: ^3.0.17 + randombytes: ^2.1.0 + safe-buffer: ^5.1.2 + scrypt-js: ^3.0.0 + secp256k1: ^4.0.1 + setimmediate: ^1.0.5 + checksum: 54bae7a4a96bd81398cdc35c91cfcc74339f71a95ed1b5b694663782e69e8e3afd21357de3b8bac9ff4877fd6f043601e200a7ad9133d94be6fd7d898ee0a449 languageName: node linkType: hard -"fragment-cache@npm:^0.2.1": - version: 0.2.1 - resolution: "fragment-cache@npm:0.2.1" +"ethereum-cryptography@npm:^1.0.3": + version: 1.1.2 + resolution: "ethereum-cryptography@npm:1.1.2" dependencies: - map-cache: ^0.2.2 - checksum: 1cbbd0b0116b67d5790175de0038a11df23c1cd2e8dcdbade58ebba5594c2d641dade6b4f126d82a7b4a6ffc2ea12e3d387dbb64ea2ae97cf02847d436f60fdc - languageName: node - linkType: hard - -"fresh@npm:0.5.2": - version: 0.5.2 - resolution: "fresh@npm:0.5.2" - checksum: 13ea8b08f91e669a64e3ba3a20eb79d7ca5379a81f1ff7f4310d54e2320645503cc0c78daedc93dfb6191287295f6479544a649c64d8e41a1c0fb0c221552346 + "@noble/hashes": 1.1.2 + "@noble/secp256k1": 1.6.3 + "@scure/bip32": 1.1.0 + "@scure/bip39": 1.1.0 + checksum: 0ef55f141acad45b1ba1db58ce3d487155eb2d0b14a77b3959167a36ad324f46762873257def75e7f00dbe8ac78aabc323d2207830f85e63a42a1fb67063a6ba languageName: node linkType: hard -"fs-constants@npm:^1.0.0": - version: 1.0.0 - resolution: "fs-constants@npm:1.0.0" - checksum: 18f5b718371816155849475ac36c7d0b24d39a11d91348cfcb308b4494824413e03572c403c86d3a260e049465518c4f0d5bd00f0371cdfcad6d4f30a85b350d +"ethereum-cryptography@npm:^2.0.0, ethereum-cryptography@npm:^2.1.2, ethereum-cryptography@npm:^2.2.1": + version: 2.2.1 + resolution: "ethereum-cryptography@npm:2.2.1" + dependencies: + "@noble/curves": 1.4.2 + "@noble/hashes": 1.4.0 + "@scure/bip32": 1.4.0 + "@scure/bip39": 1.3.0 + checksum: 1466e4c417b315a6ac67f95088b769fafac8902b495aada3c6375d827e5a7882f9e0eea5f5451600d2250283d9198b8a3d4d996e374e07a80a324e29136f25c6 languageName: node linkType: hard -"fs-extra@npm:9.1.0, fs-extra@npm:^9.1.0": - version: 9.1.0 - resolution: "fs-extra@npm:9.1.0" +"ethereumjs-abi@npm:^0.6.8": + version: 0.6.8 + resolution: "ethereumjs-abi@npm:0.6.8" dependencies: - at-least-node: ^1.0.0 - graceful-fs: ^4.2.0 - jsonfile: ^6.0.1 - universalify: ^2.0.0 - checksum: ba71ba32e0faa74ab931b7a0031d1523c66a73e225de7426e275e238e312d07313d2da2d33e34a52aa406c8763ade5712eb3ec9ba4d9edce652bcacdc29e6b20 + bn.js: ^4.11.8 + ethereumjs-util: ^6.0.0 + checksum: cede2a8ae7c7e04eeaec079c2f925601a25b2ef75cf9230e7c5da63b4ea27883b35447365a47e35c1e831af520973a2252af89022c292c18a09a4607821a366b languageName: node linkType: hard -"fs-extra@npm:^0.30.0": - version: 0.30.0 - resolution: "fs-extra@npm:0.30.0" +"ethereumjs-util@npm:^5.1.1": + version: 5.2.1 + resolution: "ethereumjs-util@npm:5.2.1" dependencies: - graceful-fs: ^4.1.2 - jsonfile: ^2.1.0 - klaw: ^1.0.0 - path-is-absolute: ^1.0.0 - rimraf: ^2.2.8 - checksum: 6edfd65fc813baa27f1603778c0f5ec11f8c5006a20b920437813ee2023eba18aeec8bef1c89b2e6c84f9fc90fdc7c916f4a700466c8c69d22a35d018f2570f0 + bn.js: ^4.11.0 + create-hash: ^1.1.2 + elliptic: ^6.5.2 + ethereum-cryptography: ^0.1.3 + ethjs-util: ^0.1.3 + rlp: ^2.0.0 + safe-buffer: ^5.1.1 + checksum: 20db6c639d92b35739fd5f7a71e64a92e85442ea0d176b59b5cd5828265b6cf42bd4868cf81a9b20a83738db1ffa7a2f778f1d850d663627a1a5209f7904b44f languageName: node linkType: hard -"fs-extra@npm:^10.0.0": - version: 10.1.0 - resolution: "fs-extra@npm:10.1.0" +"ethereumjs-util@npm:^6.0.0": + version: 6.2.1 + resolution: "ethereumjs-util@npm:6.2.1" dependencies: - graceful-fs: ^4.2.0 - jsonfile: ^6.0.1 - universalify: ^2.0.0 - checksum: dc94ab37096f813cc3ca12f0f1b5ad6744dfed9ed21e953d72530d103cea193c2f81584a39e9dee1bea36de5ee66805678c0dddc048e8af1427ac19c00fffc50 + "@types/bn.js": ^4.11.3 + bn.js: ^4.11.0 + create-hash: ^1.1.2 + elliptic: ^6.5.2 + ethereum-cryptography: ^0.1.3 + ethjs-util: 0.1.6 + rlp: ^2.2.3 + checksum: e3cb4a2c034a2529281fdfc21a2126fe032fdc3038863f5720352daa65ddcc50fc8c67dbedf381a882dc3802e05d979287126d7ecf781504bde1fd8218693bde languageName: node linkType: hard -"fs-extra@npm:^4.0.2, fs-extra@npm:^4.0.3": - version: 4.0.3 - resolution: "fs-extra@npm:4.0.3" +"ethereumjs-util@npm:^7.0.10, ethereumjs-util@npm:^7.0.3, ethereumjs-util@npm:^7.1.5": + version: 7.1.5 + resolution: "ethereumjs-util@npm:7.1.5" dependencies: - graceful-fs: ^4.1.2 - jsonfile: ^4.0.0 - universalify: ^0.1.0 - checksum: c5ae3c7043ad7187128e619c0371da01b58694c1ffa02c36fb3f5b459925d9c27c3cb1e095d9df0a34a85ca993d8b8ff6f6ecef868fd5ebb243548afa7fc0936 + "@types/bn.js": ^5.1.0 + bn.js: ^5.1.2 + create-hash: ^1.1.2 + ethereum-cryptography: ^0.1.3 + rlp: ^2.2.4 + checksum: 27a3c79d6e06b2df34b80d478ce465b371c8458b58f5afc14d91c8564c13363ad336e6e83f57eb0bd719fde94d10ee5697ceef78b5aa932087150c5287b286d1 languageName: node linkType: hard -"fs-extra@npm:^7.0.0, fs-extra@npm:^7.0.1": - version: 7.0.1 - resolution: "fs-extra@npm:7.0.1" +"ethereumjs-util@npm:^7.1.0": + version: 7.1.3 + resolution: "ethereumjs-util@npm:7.1.3" dependencies: - graceful-fs: ^4.1.2 - jsonfile: ^4.0.0 - universalify: ^0.1.0 - checksum: 141b9dccb23b66a66cefdd81f4cda959ff89282b1d721b98cea19ba08db3dcbe6f862f28841f3cf24bb299e0b7e6c42303908f65093cb7e201708e86ea5a8dcf + "@types/bn.js": ^5.1.0 + bn.js: ^5.1.2 + create-hash: ^1.1.2 + ethereum-cryptography: ^0.1.3 + rlp: ^2.2.4 + checksum: 6de7a32af05c7265c96163ecd15ad97327afab9deb36092ef26250616657a8c0b5df8e698328247c8193e7b87c643c967f64f0b3cff2b2937cafa870ff5fcb41 languageName: node linkType: hard -"fs-extra@npm:^8.1.0": - version: 8.1.0 - resolution: "fs-extra@npm:8.1.0" +"ethers@npm:5.7.2, ethers@npm:^5.5.3, ethers@npm:^5.7.2": + version: 5.7.2 + resolution: "ethers@npm:5.7.2" dependencies: - graceful-fs: ^4.2.0 - jsonfile: ^4.0.0 - universalify: ^0.1.0 - checksum: bf44f0e6cea59d5ce071bba4c43ca76d216f89e402dc6285c128abc0902e9b8525135aa808adad72c9d5d218e9f4bcc63962815529ff2f684ad532172a284880 + "@ethersproject/abi": 5.7.0 + "@ethersproject/abstract-provider": 5.7.0 + "@ethersproject/abstract-signer": 5.7.0 + "@ethersproject/address": 5.7.0 + "@ethersproject/base64": 5.7.0 + "@ethersproject/basex": 5.7.0 + "@ethersproject/bignumber": 5.7.0 + "@ethersproject/bytes": 5.7.0 + "@ethersproject/constants": 5.7.0 + "@ethersproject/contracts": 5.7.0 + "@ethersproject/hash": 5.7.0 + "@ethersproject/hdnode": 5.7.0 + "@ethersproject/json-wallets": 5.7.0 + "@ethersproject/keccak256": 5.7.0 + "@ethersproject/logger": 5.7.0 + "@ethersproject/networks": 5.7.1 + "@ethersproject/pbkdf2": 5.7.0 + "@ethersproject/properties": 5.7.0 + "@ethersproject/providers": 5.7.2 + "@ethersproject/random": 5.7.0 + "@ethersproject/rlp": 5.7.0 + "@ethersproject/sha2": 5.7.0 + "@ethersproject/signing-key": 5.7.0 + "@ethersproject/solidity": 5.7.0 + "@ethersproject/strings": 5.7.0 + "@ethersproject/transactions": 5.7.0 + "@ethersproject/units": 5.7.0 + "@ethersproject/wallet": 5.7.0 + "@ethersproject/web": 5.7.1 + "@ethersproject/wordlists": 5.7.0 + checksum: b7c08cf3e257185a7946117dbbf764433b7ba0e77c27298dec6088b3bc871aff711462b0621930c56880ff0a7ceb8b1d3a361ffa259f93377b48e34107f62553 languageName: node linkType: hard -"fs-jetpack@npm:4.3.1": - version: 4.3.1 - resolution: "fs-jetpack@npm:4.3.1" +"ethers@npm:^4.0.40": + version: 4.0.49 + resolution: "ethers@npm:4.0.49" dependencies: - minimatch: ^3.0.2 - rimraf: ^2.6.3 - checksum: ffe90946ec250c6042569faa2ec7753594779ca0e8a72eea0b76b82574542c50d580974f54c5d6885f44f5719ece173be778cf82dc50ad90f43dab043f4061c9 + aes-js: 3.0.0 + bn.js: ^4.11.9 + elliptic: 6.5.4 + hash.js: 1.1.3 + js-sha3: 0.5.7 + scrypt-js: 2.0.4 + setimmediate: 1.0.4 + uuid: 2.0.1 + xmlhttprequest: 1.8.0 + checksum: 357115348a5f1484c7745fae1d852876788216c7d94c072c80132192f1800c4d388433ea2456750856641d6d4eed8a3b41847eb44f5e1c42139963864e3bcc38 languageName: node linkType: hard -"fs-minipass@npm:^1.2.7": - version: 1.2.7 - resolution: "fs-minipass@npm:1.2.7" +"ethers@npm:^6.7.0": + version: 6.7.0 + resolution: "ethers@npm:6.7.0" dependencies: - minipass: ^2.6.0 - checksum: 40fd46a2b5dcb74b3a580269f9a0c36f9098c2ebd22cef2e1a004f375b7b665c11f1507ec3f66ee6efab5664109f72d0a74ea19c3370842214c3da5168d6fdd7 + "@adraffy/ens-normalize": 1.9.2 + "@noble/hashes": 1.1.2 + "@noble/secp256k1": 1.7.1 + "@types/node": 18.15.13 + aes-js: 4.0.0-beta.5 + tslib: 2.4.0 + ws: 8.5.0 + checksum: 6d2ea085010da1c34750ce4a00a94d2abbeb3ababb23aa754acc7772682f145e8c1b3862d3b5374e1c182aee569c80ea48191107d469a4de3b0dd6af3d9ce6db languageName: node linkType: hard -"fs-minipass@npm:^2.0.0": - version: 2.1.0 - resolution: "fs-minipass@npm:2.1.0" +"ethjs-unit@npm:0.1.6": + version: 0.1.6 + resolution: "ethjs-unit@npm:0.1.6" dependencies: - minipass: ^3.0.0 - checksum: 1b8d128dae2ac6cc94230cc5ead341ba3e0efaef82dab46a33d171c044caaa6ca001364178d42069b2809c35a1c3c35079a32107c770e9ffab3901b59af8c8b1 + bn.js: 4.11.6 + number-to-bn: 1.7.0 + checksum: df6b4752ff7461a59a20219f4b1684c631ea601241c39660e3f6c6bd63c950189723841c22b3c6c0ebeb3c9fc99e0e803e3c613101206132603705fcbcf4def5 languageName: node linkType: hard -"fs-promise@npm:^0.3.1": - version: 0.3.1 - resolution: "fs-promise@npm:0.3.1" +"ethjs-util@npm:0.1.6, ethjs-util@npm:^0.1.3": + version: 0.1.6 + resolution: "ethjs-util@npm:0.1.6" dependencies: - any-promise: ~0.1.0 - checksum: b67515925e695fbacc24d081567f2b2efe23e1936248916d619a5f545f5e320074d4164ce06c79e7f984fb0ee4878712b36bb9016f11435618e25b27817095a1 + is-hex-prefixed: 1.0.0 + strip-hex-prefix: 1.0.0 + checksum: 1f42959e78ec6f49889c49c8a98639e06f52a15966387dd39faf2930db48663d026efb7db2702dcffe7f2a99c4a0144b7ce784efdbf733f4077aae95de76d65f languageName: node linkType: hard -"fs-readdir-recursive@npm:^1.1.0": - version: 1.1.0 - resolution: "fs-readdir-recursive@npm:1.1.0" - checksum: 29d50f3d2128391c7fc9fd051c8b7ea45bcc8aa84daf31ef52b17218e20bfd2bd34d02382742801954cc8d1905832b68227f6b680a666ce525d8b6b75068ad1e +"event-target-shim@npm:^5.0.0": + version: 5.0.1 + resolution: "event-target-shim@npm:5.0.1" + checksum: 1ffe3bb22a6d51bdeb6bf6f7cf97d2ff4a74b017ad12284cc9e6a279e727dc30a5de6bb613e5596ff4dc3e517841339ad09a7eec44266eccb1aa201a30448166 languageName: node linkType: hard -"fs.realpath@npm:^1.0.0": - version: 1.0.0 - resolution: "fs.realpath@npm:1.0.0" - checksum: 99ddea01a7e75aa276c250a04eedeffe5662bce66c65c07164ad6264f9de18fb21be9433ead460e54cff20e31721c811f4fb5d70591799df5f85dce6d6746fd0 +"eventemitter3@npm:4.0.4": + version: 4.0.4 + resolution: "eventemitter3@npm:4.0.4" + checksum: 7afb1cd851d19898bc99cc55ca894fe18cb1f8a07b0758652830a09bd6f36082879a25345be6219b81d74764140688b1a8fa75bcd1073d96b9a6661e444bc2ea languageName: node linkType: hard -"fsevents@npm:~2.1.1": - version: 2.1.3 - resolution: "fsevents@npm:2.1.3" - dependencies: - node-gyp: latest - checksum: b5ec0516b44d75b60af5c01ff80a80cd995d175e4640d2a92fbabd02991dd664d76b241b65feef0775c23d531c3c74742c0fbacd6205af812a9c3cef59f04292 - conditions: os=darwin +"eventemitter3@npm:5.0.1": + version: 5.0.1 + resolution: "eventemitter3@npm:5.0.1" + checksum: 543d6c858ab699303c3c32e0f0f47fc64d360bf73c3daf0ac0b5079710e340d6fe9f15487f94e66c629f5f82cd1a8678d692f3dbb6f6fcd1190e1b97fcad36f8 languageName: node linkType: hard -"fsevents@npm:~2.3.2": - version: 2.3.2 - resolution: "fsevents@npm:2.3.2" - dependencies: - node-gyp: latest - checksum: 97ade64e75091afee5265e6956cb72ba34db7819b4c3e94c431d4be2b19b8bb7a2d4116da417950c3425f17c8fe693d25e20212cac583ac1521ad066b77ae31f - conditions: os=darwin +"events@npm:^3.3.0": + version: 3.3.0 + resolution: "events@npm:3.3.0" + checksum: f6f487ad2198aa41d878fa31452f1a3c00958f46e9019286ff4787c84aac329332ab45c9cdc8c445928fc6d7ded294b9e005a7fce9426488518017831b272780 languageName: node linkType: hard -"fsevents@patch:fsevents@~2.1.1#~builtin": - version: 2.1.3 - resolution: "fsevents@patch:fsevents@npm%3A2.1.3#~builtin::version=2.1.3&hash=31d12a" +"evp_bytestokey@npm:^1.0.0, evp_bytestokey@npm:^1.0.3": + version: 1.0.3 + resolution: "evp_bytestokey@npm:1.0.3" dependencies: + md5.js: ^1.3.4 node-gyp: latest - conditions: os=darwin + safe-buffer: ^5.1.1 + checksum: ad4e1577f1a6b721c7800dcc7c733fe01f6c310732bb5bf2240245c2a5b45a38518b91d8be2c610611623160b9d1c0e91f1ce96d639f8b53e8894625cf20fa45 languageName: node linkType: hard -"fsevents@patch:fsevents@~2.3.2#~builtin": - version: 2.3.2 - resolution: "fsevents@patch:fsevents@npm%3A2.3.2#~builtin::version=2.3.2&hash=df0bf1" +"execa@npm:5.1.1": + version: 5.1.1 + resolution: "execa@npm:5.1.1" dependencies: - node-gyp: latest - conditions: os=darwin + cross-spawn: ^7.0.3 + get-stream: ^6.0.0 + human-signals: ^2.1.0 + is-stream: ^2.0.0 + merge-stream: ^2.0.0 + npm-run-path: ^4.0.1 + onetime: ^5.1.2 + signal-exit: ^3.0.3 + strip-final-newline: ^2.0.0 + checksum: fba9022c8c8c15ed862847e94c252b3d946036d7547af310e344a527e59021fd8b6bb0723883ea87044dc4f0201f949046993124a42ccb0855cae5bf8c786343 languageName: node linkType: hard -"function-bind@npm:^1.1.1": +"exit-hook@npm:^1.0.0": version: 1.1.1 - resolution: "function-bind@npm:1.1.1" - checksum: b32fbaebb3f8ec4969f033073b43f5c8befbb58f1a79e12f1d7490358150359ebd92f49e72ff0144f65f2c48ea2a605bff2d07965f548f6474fd8efd95bf361a + resolution: "exit-hook@npm:1.1.1" + checksum: 1b4f16da7c202cd336ca07acb052922639182b4e2f1ad4007ed481bb774ce93469f505dec1371d9cd580ac54146a9fd260f053b0e4a48fa87c49fa3dc4a3f144 languageName: node linkType: hard -"function.prototype.name@npm:^1.1.5": - version: 1.1.5 - resolution: "function.prototype.name@npm:1.1.5" - dependencies: - call-bind: ^1.0.2 - define-properties: ^1.1.3 - es-abstract: ^1.19.0 - functions-have-names: ^1.2.2 - checksum: acd21d733a9b649c2c442f067567743214af5fa248dbeee69d8278ce7df3329ea5abac572be9f7470b4ec1cd4d8f1040e3c5caccf98ebf2bf861a0deab735c27 +"expand-template@npm:^2.0.3": + version: 2.0.3 + resolution: "expand-template@npm:2.0.3" + checksum: 588c19847216421ed92befb521767b7018dc88f88b0576df98cb242f20961425e96a92cbece525ef28cc5becceae5d544ae0f5b9b5e2aa05acb13716ca5b3099 languageName: node linkType: hard -"function.prototype.name@npm:^1.1.6": - version: 1.1.6 - resolution: "function.prototype.name@npm:1.1.6" +"express@npm:^4.14.0": + version: 4.18.2 + resolution: "express@npm:4.18.2" dependencies: - call-bind: ^1.0.2 - define-properties: ^1.2.0 - es-abstract: ^1.22.1 - functions-have-names: ^1.2.3 - checksum: 7a3f9bd98adab09a07f6e1f03da03d3f7c26abbdeaeee15223f6c04a9fb5674792bdf5e689dac19b97ac71de6aad2027ba3048a9b883aa1b3173eed6ab07f479 + accepts: ~1.3.8 + array-flatten: 1.1.1 + body-parser: 1.20.1 + content-disposition: 0.5.4 + content-type: ~1.0.4 + cookie: 0.5.0 + cookie-signature: 1.0.6 + debug: 2.6.9 + depd: 2.0.0 + encodeurl: ~1.0.2 + escape-html: ~1.0.3 + etag: ~1.8.1 + finalhandler: 1.2.0 + fresh: 0.5.2 + http-errors: 2.0.0 + merge-descriptors: 1.0.1 + methods: ~1.1.2 + on-finished: 2.4.1 + parseurl: ~1.3.3 + path-to-regexp: 0.1.7 + proxy-addr: ~2.0.7 + qs: 6.11.0 + range-parser: ~1.2.1 + safe-buffer: 5.2.1 + send: 0.18.0 + serve-static: 1.15.0 + setprototypeof: 1.2.0 + statuses: 2.0.1 + type-is: ~1.6.18 + utils-merge: 1.0.1 + vary: ~1.1.2 + checksum: 3c4b9b076879442f6b968fe53d85d9f1eeacbb4f4c41e5f16cc36d77ce39a2b0d81b3f250514982110d815b2f7173f5561367f9110fcc541f9371948e8c8b037 languageName: node linkType: hard -"functional-red-black-tree@npm:^1.0.1, functional-red-black-tree@npm:~1.0.1": - version: 1.0.1 - resolution: "functional-red-black-tree@npm:1.0.1" - checksum: ca6c170f37640e2d94297da8bb4bf27a1d12bea3e00e6a3e007fd7aa32e37e000f5772acf941b4e4f3cf1c95c3752033d0c509af157ad8f526e7f00723b9eb9f +"ext@npm:^1.1.2": + version: 1.7.0 + resolution: "ext@npm:1.7.0" + dependencies: + type: ^2.7.2 + checksum: ef481f9ef45434d8c867cfd09d0393b60945b7c8a1798bedc4514cb35aac342ccb8d8ecb66a513e6a2b4ec1e294a338e3124c49b29736f8e7c735721af352c31 languageName: node linkType: hard -"functions-have-names@npm:^1.2.2, functions-have-names@npm:^1.2.3": - version: 1.2.3 - resolution: "functions-have-names@npm:1.2.3" - checksum: c3f1f5ba20f4e962efb71344ce0a40722163e85bee2101ce25f88214e78182d2d2476aa85ef37950c579eb6cf6ee811c17b3101bb84004bb75655f3e33f3fdb5 +"extend@npm:~3.0.2": + version: 3.0.2 + resolution: "extend@npm:3.0.2" + checksum: a50a8309ca65ea5d426382ff09f33586527882cf532931cb08ca786ea3146c0553310bda688710ff61d7668eba9f96b923fe1420cdf56a2c3eaf30fcab87b515 languageName: node linkType: hard -"ganache-cli@npm:^6.12.2": - version: 6.12.2 - resolution: "ganache-cli@npm:6.12.2" +"external-editor@npm:^3.0.3": + version: 3.1.0 + resolution: "external-editor@npm:3.1.0" dependencies: - ethereumjs-util: 6.2.1 - source-map-support: 0.5.12 - yargs: 13.2.4 - bin: - ganache-cli: cli.js - checksum: dd314c1b44f2fec3f9fcd7f5857c23045b480ed8cf23e9939166f027799d3cc0a58e5fe4d7f3f44371835b6f777de8eefae3af5b49904eeccc8acea99a6239d6 + chardet: ^0.7.0 + iconv-lite: ^0.4.24 + tmp: ^0.0.33 + checksum: 1c2a616a73f1b3435ce04030261bed0e22d4737e14b090bb48e58865da92529c9f2b05b893de650738d55e692d071819b45e1669259b2b354bc3154d27a698c7 languageName: node linkType: hard -"ganache-core@npm:^2.13.2": - version: 2.13.2 - resolution: "ganache-core@npm:2.13.2" - dependencies: - abstract-leveldown: 3.0.0 - async: 2.6.2 - bip39: 2.5.0 - cachedown: 1.0.0 - clone: 2.1.2 - debug: 3.2.6 - encoding-down: 5.0.4 - eth-sig-util: 3.0.0 - ethereumjs-abi: 0.6.8 - ethereumjs-account: 3.0.0 - ethereumjs-block: 2.2.2 - ethereumjs-common: 1.5.0 - ethereumjs-tx: 2.1.2 - ethereumjs-util: 6.2.1 - ethereumjs-vm: 4.2.0 - ethereumjs-wallet: 0.6.5 - heap: 0.2.6 - keccak: 3.0.1 - level-sublevel: 6.6.4 - levelup: 3.1.1 - lodash: 4.17.20 - lru-cache: 5.1.1 - merkle-patricia-tree: 3.0.0 - patch-package: 6.2.2 - seedrandom: 3.0.1 - source-map-support: 0.5.12 - tmp: 0.1.0 - web3: 1.2.11 - web3-provider-engine: 14.2.1 - websocket: 1.0.32 - dependenciesMeta: - ethereumjs-wallet: - optional: true - web3: - optional: true - checksum: 799b275abd09259c88a4e78c335e807d14cc12d3a1ceb9d7cdeef484cf5fab541847edf9cf209f448190199dbd0796393d308d50e6823565154c17dd0c3a4048 +"extsprintf@npm:1.3.0": + version: 1.3.0 + resolution: "extsprintf@npm:1.3.0" + checksum: cee7a4a1e34cffeeec18559109de92c27517e5641991ec6bab849aa64e3081022903dd53084f2080d0d2530803aa5ee84f1e9de642c365452f9e67be8f958ce2 languageName: node linkType: hard -"gauge@npm:~2.7.3": - version: 2.7.4 - resolution: "gauge@npm:2.7.4" - dependencies: - aproba: ^1.0.3 - console-control-strings: ^1.0.0 - has-unicode: ^2.0.0 - object-assign: ^4.1.0 - signal-exit: ^3.0.0 - string-width: ^1.0.1 - strip-ansi: ^3.0.1 - wide-align: ^1.1.0 - checksum: a89b53cee65579b46832e050b5f3a79a832cc422c190de79c6b8e2e15296ab92faddde6ddf2d376875cbba2b043efa99b9e1ed8124e7365f61b04e3cee9d40ee +"extsprintf@npm:^1.2.0": + version: 1.4.0 + resolution: "extsprintf@npm:1.4.0" + checksum: 184dc8a413eb4b1ff16bdce797340e7ded4d28511d56a1c9afa5a95bcff6ace154063823eaf0206dbbb0d14059d74f382a15c34b7c0636fa74a7e681295eb67e languageName: node linkType: hard -"get-caller-file@npm:^1.0.1": - version: 1.0.3 - resolution: "get-caller-file@npm:1.0.3" - checksum: 2b90a7f848896abcebcdc0acc627a435bcf05b9cd280599bc980ebfcdc222416c3df12c24c4845f69adc4346728e8966f70b758f9369f3534182791dfbc25c05 +"eyes@npm:^0.1.8": + version: 0.1.8 + resolution: "eyes@npm:0.1.8" + checksum: c31703a92bf36ba75ee8d379ee7985c24ee6149f3a6175f44cec7a05b178c38bce9836d3ca48c9acb0329a960ac2c4b2ead4e60cdd4fe6e8c92cad7cd6913687 languageName: node linkType: hard -"get-caller-file@npm:^2.0.1, get-caller-file@npm:^2.0.5": - version: 2.0.5 - resolution: "get-caller-file@npm:2.0.5" - checksum: b9769a836d2a98c3ee734a88ba712e62703f1df31b94b784762c433c27a386dd6029ff55c2a920c392e33657d80191edbf18c61487e198844844516f843496b9 +"fast-base64-decode@npm:^1.0.0": + version: 1.0.0 + resolution: "fast-base64-decode@npm:1.0.0" + checksum: 4c59eb1775a7f132333f296c5082476fdcc8f58d023c42ed6d378d2e2da4c328c7a71562f271181a725dd17cdaa8f2805346cc330cdbad3b8e4b9751508bd0a3 languageName: node linkType: hard -"get-func-name@npm:^2.0.0": - version: 2.0.0 - resolution: "get-func-name@npm:2.0.0" - checksum: 8d82e69f3e7fab9e27c547945dfe5cc0c57fc0adf08ce135dddb01081d75684a03e7a0487466f478872b341d52ac763ae49e660d01ab83741f74932085f693c3 +"fast-decode-uri-component@npm:^1.0.1": + version: 1.0.1 + resolution: "fast-decode-uri-component@npm:1.0.1" + checksum: 427a48fe0907e76f0e9a2c228e253b4d8a8ab21d130ee9e4bb8339c5ba4086235cf9576831f7b20955a752eae4b525a177ff9d5825dd8d416e7726939194fbee languageName: node linkType: hard -"get-intrinsic@npm:^1.0.2, get-intrinsic@npm:^1.1.0, get-intrinsic@npm:^1.1.1": - version: 1.1.1 - resolution: "get-intrinsic@npm:1.1.1" - dependencies: - function-bind: ^1.1.1 - has: ^1.0.3 - has-symbols: ^1.0.1 - checksum: a9fe2ca8fa3f07f9b0d30fb202bcd01f3d9b9b6b732452e79c48e79f7d6d8d003af3f9e38514250e3553fdc83c61650851cb6870832ac89deaaceb08e3721a17 +"fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": + version: 3.1.3 + resolution: "fast-deep-equal@npm:3.1.3" + checksum: e21a9d8d84f53493b6aa15efc9cfd53dd5b714a1f23f67fb5dc8f574af80df889b3bce25dc081887c6d25457cce704e636395333abad896ccdec03abaf1f3f9d languageName: node linkType: hard -"get-intrinsic@npm:^1.1.3": - version: 1.1.3 - resolution: "get-intrinsic@npm:1.1.3" - dependencies: - function-bind: ^1.1.1 - has: ^1.0.3 - has-symbols: ^1.0.3 - checksum: 152d79e87251d536cf880ba75cfc3d6c6c50e12b3a64e1ea960e73a3752b47c69f46034456eae1b0894359ce3bc64c55c186f2811f8a788b75b638b06fab228a +"fast-diff@npm:^1.1.2": + version: 1.2.0 + resolution: "fast-diff@npm:1.2.0" + checksum: 1b5306eaa9e826564d9e5ffcd6ebd881eb5f770b3f977fcbf38f05c824e42172b53c79920e8429c54eb742ce15a0caf268b0fdd5b38f6de52234c4a8368131ae languageName: node linkType: hard -"get-intrinsic@npm:^1.2.0, get-intrinsic@npm:^1.2.1": - version: 1.2.1 - resolution: "get-intrinsic@npm:1.2.1" - dependencies: - function-bind: ^1.1.1 - has: ^1.0.3 - has-proto: ^1.0.1 - has-symbols: ^1.0.3 - checksum: 5b61d88552c24b0cf6fa2d1b3bc5459d7306f699de060d76442cce49a4721f52b8c560a33ab392cf5575b7810277d54ded9d4d39a1ea61855619ebc005aa7e5f +"fast-fifo@npm:^1.0.0": + version: 1.3.0 + resolution: "fast-fifo@npm:1.3.0" + checksum: edc589b818eede61d0048f399daf67cbc5ef736588669482a20f37269b4808356e54ab89676fd8fa59b26c216c11e5ac57335cc70dca54fbbf692d4acde10de6 languageName: node linkType: hard -"get-iterator@npm:^1.0.2": - version: 1.0.2 - resolution: "get-iterator@npm:1.0.2" - checksum: 4a819aa91ecb61f4fd507bd62e3468d55f642f06011f944c381a739a21f685c36a37feb9324c8971e7c0fc70ca172066c45874fa2d1dcdf4b4fb8e43f16058c2 +"fast-glob@npm:^3.0.3": + version: 3.2.12 + resolution: "fast-glob@npm:3.2.12" + dependencies: + "@nodelib/fs.stat": ^2.0.2 + "@nodelib/fs.walk": ^1.2.3 + glob-parent: ^5.1.2 + merge2: ^1.3.0 + micromatch: ^4.0.4 + checksum: 0b1990f6ce831c7e28c4d505edcdaad8e27e88ab9fa65eedadb730438cfc7cde4910d6c975d6b7b8dc8a73da4773702ebcfcd6e3518e73938bb1383badfe01c2 languageName: node linkType: hard -"get-package-type@npm:^0.1.0": - version: 0.1.0 - resolution: "get-package-type@npm:0.1.0" - checksum: bba0811116d11e56d702682ddef7c73ba3481f114590e705fc549f4d868972263896af313c57a25c076e3c0d567e11d919a64ba1b30c879be985fc9d44f96148 +"fast-glob@npm:^3.2.9": + version: 3.3.0 + resolution: "fast-glob@npm:3.3.0" + dependencies: + "@nodelib/fs.stat": ^2.0.2 + "@nodelib/fs.walk": ^1.2.3 + glob-parent: ^5.1.2 + merge2: ^1.3.0 + micromatch: ^4.0.4 + checksum: 20df62be28eb5426fe8e40e0d05601a63b1daceb7c3d87534afcad91bdcf1e4b1743cf2d5247d6e225b120b46df0b9053a032b2691ba34ee121e033acd81f547 languageName: node linkType: hard -"get-port@npm:^3.1.0": - version: 3.2.0 - resolution: "get-port@npm:3.2.0" - checksum: 31f530326569683ac4b7452eb7573c40e9dbe52aec14d80745c35475261e6389160da153d5b8ae911150b4ce99003472b30c69ba5be0cedeaa7865b95542d168 +"fast-json-stable-stringify@npm:^2.0.0": + version: 2.1.0 + resolution: "fast-json-stable-stringify@npm:2.1.0" + checksum: b191531e36c607977e5b1c47811158733c34ccb3bfde92c44798929e9b4154884378536d26ad90dfecd32e1ffc09c545d23535ad91b3161a27ddbb8ebe0cbecb languageName: node linkType: hard -"get-stdin@npm:^8.0.0": - version: 8.0.0 - resolution: "get-stdin@npm:8.0.0" - checksum: 40128b6cd25781ddbd233344f1a1e4006d4284906191ed0a7d55ec2c1a3e44d650f280b2c9eeab79c03ac3037da80257476c0e4e5af38ddfb902d6ff06282d77 +"fast-levenshtein@npm:^2.0.6, fast-levenshtein@npm:~2.0.6": + version: 2.0.6 + resolution: "fast-levenshtein@npm:2.0.6" + checksum: 92cfec0a8dfafd9c7a15fba8f2cc29cd0b62b85f056d99ce448bbcd9f708e18ab2764bda4dd5158364f4145a7c72788538994f0d1787b956ef0d1062b0f7c24c languageName: node linkType: hard -"get-stream@npm:^4.0.0, get-stream@npm:^4.1.0": - version: 4.1.0 - resolution: "get-stream@npm:4.1.0" +"fast-levenshtein@npm:^3.0.0": + version: 3.0.0 + resolution: "fast-levenshtein@npm:3.0.0" dependencies: - pump: ^3.0.0 - checksum: 443e1914170c15bd52ff8ea6eff6dfc6d712b031303e36302d2778e3de2506af9ee964d6124010f7818736dcfde05c04ba7ca6cc26883106e084357a17ae7d73 + fastest-levenshtein: ^1.0.7 + checksum: 02732ba6c656797ca7e987c25f3e53718c8fcc39a4bfab46def78eef7a8729eb629632d4a7eca4c27a33e10deabffa9984839557e18a96e91ecf7ccaeedb9890 languageName: node linkType: hard -"get-stream@npm:^5.1.0": - version: 5.2.0 - resolution: "get-stream@npm:5.2.0" +"fast-querystring@npm:^1.1.1": + version: 1.1.2 + resolution: "fast-querystring@npm:1.1.2" dependencies: - pump: ^3.0.0 - checksum: 8bc1a23174a06b2b4ce600df38d6c98d2ef6d84e020c1ddad632ad75bac4e092eeb40e4c09e0761c35fc2dbc5e7fff5dab5e763a383582c4a167dd69a905bd12 - languageName: node - linkType: hard - -"get-stream@npm:^6.0.0, get-stream@npm:^6.0.1": - version: 6.0.1 - resolution: "get-stream@npm:6.0.1" - checksum: e04ecece32c92eebf5b8c940f51468cd53554dcbb0ea725b2748be583c9523d00128137966afce410b9b051eb2ef16d657cd2b120ca8edafcf5a65e81af63cad + fast-decode-uri-component: ^1.0.1 + checksum: 7149f82ee9ac39a9c08c7ffe435b9f6deade76ae5e3675fe1835720513e8c4bc541e666b4b7b1c0c07e08f369dcf4828d00f2bee39889a90a168e1439cf27b0b languageName: node linkType: hard -"get-symbol-description@npm:^1.0.0": - version: 1.0.0 - resolution: "get-symbol-description@npm:1.0.0" +"fast-url-parser@npm:^1.1.3": + version: 1.1.3 + resolution: "fast-url-parser@npm:1.1.3" dependencies: - call-bind: ^1.0.2 - get-intrinsic: ^1.1.1 - checksum: 9ceff8fe968f9270a37a1f73bf3f1f7bda69ca80f4f80850670e0e7b9444ff99323f7ac52f96567f8b5f5fbe7ac717a0d81d3407c7313e82810c6199446a5247 + punycode: ^1.3.2 + checksum: 5043d0c4a8d775ff58504d56c096563c11b113e4cb8a2668c6f824a1cd4fb3812e2fdf76537eb24a7ce4ae7def6bd9747da630c617cf2a4b6ce0c42514e4f21c languageName: node linkType: hard -"get-value@npm:^2.0.3, get-value@npm:^2.0.6": - version: 2.0.6 - resolution: "get-value@npm:2.0.6" - checksum: 5c3b99cb5398ea8016bf46ff17afc5d1d286874d2ad38ca5edb6e87d75c0965b0094cb9a9dddef2c59c23d250702323539a7fbdd870620db38c7e7d7ec87c1eb +"fastest-levenshtein@npm:^1.0.7": + version: 1.0.16 + resolution: "fastest-levenshtein@npm:1.0.16" + checksum: a78d44285c9e2ae2c25f3ef0f8a73f332c1247b7ea7fb4a191e6bb51aa6ee1ef0dfb3ed113616dcdc7023e18e35a8db41f61c8d88988e877cf510df8edafbc71 languageName: node linkType: hard -"getpass@npm:^0.1.1": - version: 0.1.7 - resolution: "getpass@npm:0.1.7" +"fastq@npm:^1.6.0": + version: 1.13.0 + resolution: "fastq@npm:1.13.0" dependencies: - assert-plus: ^1.0.0 - checksum: ab18d55661db264e3eac6012c2d3daeafaab7a501c035ae0ccb193c3c23e9849c6e29b6ac762b9c2adae460266f925d55a3a2a3a3c8b94be2f222df94d70c046 + reusify: ^1.0.4 + checksum: 32cf15c29afe622af187d12fc9cd93e160a0cb7c31a3bb6ace86b7dea3b28e7b72acde89c882663f307b2184e14782c6c664fa315973c03626c7d4bff070bb0b languageName: node linkType: hard -"ghost-testrpc@npm:^0.0.2": - version: 0.0.2 - resolution: "ghost-testrpc@npm:0.0.2" - dependencies: - chalk: ^2.4.2 - node-emoji: ^1.10.0 - bin: - testrpc-sc: ./index.js - checksum: 3f86326d32f5e96c9356381837edde7dd0f23dcb7223aa73e02816256b84703cb76ce922987054a05b65963326088e99a4aa142d4b467ddda7c28547ed915d6d +"fdir@npm:^6.5.0": + version: 6.5.0 + resolution: "fdir@npm:6.5.0" + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + checksum: bd537daa9d3cd53887eed35efa0eab2dbb1ca408790e10e024120e7a36c6e9ae2b33710cb8381e35def01bc9c1d7eaba746f886338413e68ff6ebaee07b9a6e8 languageName: node linkType: hard -"github-from-package@npm:0.0.0": - version: 0.0.0 - resolution: "github-from-package@npm:0.0.0" - checksum: 14e448192a35c1e42efee94c9d01a10f42fe790375891a24b25261246ce9336ab9df5d274585aedd4568f7922246c2a78b8a8cd2571bfe99c693a9718e7dd0e3 +"figures@npm:^1.3.5": + version: 1.7.0 + resolution: "figures@npm:1.7.0" + dependencies: + escape-string-regexp: ^1.0.5 + object-assign: ^4.1.0 + checksum: d77206deba991a7977f864b8c8edf9b8b43b441be005482db04b0526e36263adbdb22c1c6d2df15a1ad78d12029bd1aa41ccebcb5d425e1f2cf629c6daaa8e10 languageName: node linkType: hard -"glob-parent@npm:^5.1.2, glob-parent@npm:~5.1.0, glob-parent@npm:~5.1.2": - version: 5.1.2 - resolution: "glob-parent@npm:5.1.2" +"figures@npm:^2.0.0": + version: 2.0.0 + resolution: "figures@npm:2.0.0" dependencies: - is-glob: ^4.0.1 - checksum: f4f2bfe2425296e8a47e36864e4f42be38a996db40420fe434565e4480e3322f18eb37589617a98640c5dc8fdec1a387007ee18dbb1f3f5553409c34d17f425e + escape-string-regexp: ^1.0.5 + checksum: 081beb16ea57d1716f8447c694f637668322398b57017b20929376aaf5def9823b35245b734cdd87e4832dc96e9c6f46274833cada77bfe15e5f980fea1fd21f languageName: node linkType: hard -"glob-promise@npm:^1.0.4": - version: 1.0.6 - resolution: "glob-promise@npm:1.0.6" +"file-entry-cache@npm:^5.0.1": + version: 5.0.1 + resolution: "file-entry-cache@npm:5.0.1" dependencies: - glob: "*" - checksum: 650a663697c6cb03caf32c4ab9200ca5b6e796f051af52f42a2c491b98da4a856f6102815253207b2fd3ebe114db867b11b19f1aaa7e4c72040e52170c7d5090 + flat-cache: ^2.0.1 + checksum: 9014b17766815d59b8b789633aed005242ef857348c09be558bd85b4a24e16b0ad1e0e5229ccea7a2109f74ef1b3db1a559b58afe12b884f09019308711376fd languageName: node linkType: hard -"glob@npm:*": - version: 9.2.1 - resolution: "glob@npm:9.2.1" +"file-entry-cache@npm:^6.0.1": + version: 6.0.1 + resolution: "file-entry-cache@npm:6.0.1" dependencies: - fs.realpath: ^1.0.0 - minimatch: ^7.4.1 - minipass: ^4.2.4 - path-scurry: ^1.6.1 - checksum: ef9b1c32491e6b532bdd0d2abcc3c9f48e83446609e11285869156982fc5a756dfbaa6f59f797712343bd1e22500ac15708692806633653fde4ef67c85e2aab7 + flat-cache: ^3.0.4 + checksum: f49701feaa6314c8127c3c2f6173cfefff17612f5ed2daaafc6da13b5c91fd43e3b2a58fd0d63f9f94478a501b167615931e7200e31485e320f74a33885a9c74 languageName: node linkType: hard -"glob@npm:7.1.3": - version: 7.1.3 - resolution: "glob@npm:7.1.3" - dependencies: - fs.realpath: ^1.0.0 - inflight: ^1.0.4 - inherits: 2 - minimatch: ^3.0.4 - once: ^1.3.0 - path-is-absolute: ^1.0.0 - checksum: d72a834a393948d6c4a5cacc6a29fe5fe190e1cd134e55dfba09aee0be6fe15be343e96d8ec43558ab67ff8af28e4420c7f63a4d4db1c779e515015e9c318616 +"file-uri-to-path@npm:1.0.0": + version: 1.0.0 + resolution: "file-uri-to-path@npm:1.0.0" + checksum: b648580bdd893a008c92c7ecc96c3ee57a5e7b6c4c18a9a09b44fb5d36d79146f8e442578bc0e173dc027adf3987e254ba1dfd6e3ec998b7c282873010502144 languageName: node linkType: hard -"glob@npm:7.1.7": - version: 7.1.7 - resolution: "glob@npm:7.1.7" +"filelist@npm:^1.0.4": + version: 1.0.4 + resolution: "filelist@npm:1.0.4" dependencies: - fs.realpath: ^1.0.0 - inflight: ^1.0.4 - inherits: 2 - minimatch: ^3.0.4 - once: ^1.3.0 - path-is-absolute: ^1.0.0 - checksum: b61f48973bbdcf5159997b0874a2165db572b368b931135832599875919c237fc05c12984e38fe828e69aa8a921eb0e8a4997266211c517c9cfaae8a93988bb8 + minimatch: ^5.0.1 + checksum: a303573b0821e17f2d5e9783688ab6fbfce5d52aaac842790ae85e704a6f5e4e3538660a63183d6453834dedf1e0f19a9dadcebfa3e926c72397694ea11f5160 languageName: node linkType: hard -"glob@npm:7.2.0, glob@npm:^7.0.0, glob@npm:^7.1.3, glob@npm:^7.1.4": - version: 7.2.0 - resolution: "glob@npm:7.2.0" +"fill-range@npm:^7.0.1": + version: 7.0.1 + resolution: "fill-range@npm:7.0.1" dependencies: - fs.realpath: ^1.0.0 - inflight: ^1.0.4 - inherits: 2 - minimatch: ^3.0.4 - once: ^1.3.0 - path-is-absolute: ^1.0.0 - checksum: 78a8ea942331f08ed2e055cb5b9e40fe6f46f579d7fd3d694f3412fe5db23223d29b7fee1575440202e9a7ff9a72ab106a39fee39934c7bedafe5e5f8ae20134 + to-regex-range: ^5.0.1 + checksum: cc283f4e65b504259e64fd969bcf4def4eb08d85565e906b7d36516e87819db52029a76b6363d0f02d0d532f0033c9603b9e2d943d56ee3b0d4f7ad3328ff917 languageName: node linkType: hard -"glob@npm:9.3.5": - version: 9.3.5 - resolution: "glob@npm:9.3.5" +"finalhandler@npm:1.2.0": + version: 1.2.0 + resolution: "finalhandler@npm:1.2.0" dependencies: - fs.realpath: ^1.0.0 - minimatch: ^8.0.2 - minipass: ^4.2.4 - path-scurry: ^1.6.1 - checksum: 94b093adbc591bc36b582f77927d1fb0dbf3ccc231828512b017601408be98d1fe798fc8c0b19c6f2d1a7660339c3502ce698de475e9d938ccbb69b47b647c84 + debug: 2.6.9 + encodeurl: ~1.0.2 + escape-html: ~1.0.3 + on-finished: 2.4.1 + parseurl: ~1.3.3 + statuses: 2.0.1 + unpipe: ~1.0.0 + checksum: 92effbfd32e22a7dff2994acedbd9bcc3aa646a3e919ea6a53238090e87097f8ef07cced90aa2cc421abdf993aefbdd5b00104d55c7c5479a8d00ed105b45716 languageName: node linkType: hard -"glob@npm:^5.0.15": - version: 5.0.15 - resolution: "glob@npm:5.0.15" +"find-replace@npm:^3.0.0": + version: 3.0.0 + resolution: "find-replace@npm:3.0.0" dependencies: - inflight: ^1.0.4 - inherits: 2 - minimatch: 2 || 3 - once: ^1.3.0 - path-is-absolute: ^1.0.0 - checksum: f9742448303460672607e569457f1b57e486a79a985e269b69465834d2075b243378225f65dc54c09fcd4b75e4fb34442aec88f33f8c65fa4abccc8ee2dc2f5d + array-back: ^3.0.1 + checksum: 6b04bcfd79027f5b84aa1dfe100e3295da989bdac4b4de6b277f4d063e78f5c9e92ebc8a1fec6dd3b448c924ba404ee051cc759e14a3ee3e825fa1361025df08 languageName: node linkType: hard -"glob@npm:^7.1.2, glob@npm:~7.2.3": - version: 7.2.3 - resolution: "glob@npm:7.2.3" +"find-up@npm:3.0.0, find-up@npm:^3.0.0": + version: 3.0.0 + resolution: "find-up@npm:3.0.0" dependencies: - fs.realpath: ^1.0.0 - inflight: ^1.0.4 - inherits: 2 - minimatch: ^3.1.1 - once: ^1.3.0 - path-is-absolute: ^1.0.0 - checksum: 29452e97b38fa704dabb1d1045350fb2467cf0277e155aa9ff7077e90ad81d1ea9d53d3ee63bd37c05b09a065e90f16aec4a65f5b8de401d1dac40bc5605d133 + locate-path: ^3.0.0 + checksum: 38eba3fe7a66e4bc7f0f5a1366dc25508b7cfc349f852640e3678d26ad9a6d7e2c43eff0a472287de4a9753ef58f066a0ea892a256fa3636ad51b3fe1e17fae9 languageName: node linkType: hard -"global-modules@npm:^2.0.0": - version: 2.0.0 - resolution: "global-modules@npm:2.0.0" +"find-up@npm:5.0.0, find-up@npm:^5.0.0": + version: 5.0.0 + resolution: "find-up@npm:5.0.0" dependencies: - global-prefix: ^3.0.0 - checksum: d6197f25856c878c2fb5f038899f2dca7cbb2f7b7cf8999660c0104972d5cfa5c68b5a0a77fa8206bb536c3903a4615665acb9709b4d80846e1bb47eaef65430 + locate-path: ^6.0.0 + path-exists: ^4.0.0 + checksum: 07955e357348f34660bde7920783204ff5a26ac2cafcaa28bace494027158a97b9f56faaf2d89a6106211a8174db650dd9f503f9c0d526b1202d5554a00b9095 languageName: node linkType: hard -"global-prefix@npm:^3.0.0": - version: 3.0.0 - resolution: "global-prefix@npm:3.0.0" +"find-up@npm:^2.1.0": + version: 2.1.0 + resolution: "find-up@npm:2.1.0" dependencies: - ini: ^1.3.5 - kind-of: ^6.0.2 - which: ^1.3.1 - checksum: 8a82fc1d6f22c45484a4e34656cc91bf021a03e03213b0035098d605bfc612d7141f1e14a21097e8a0413b4884afd5b260df0b6a25605ce9d722e11f1df2881d + locate-path: ^2.0.0 + checksum: 43284fe4da09f89011f08e3c32cd38401e786b19226ea440b75386c1b12a4cb738c94969808d53a84f564ede22f732c8409e3cfc3f7fb5b5c32378ad0bbf28bd languageName: node linkType: hard -"global@npm:~4.4.0": - version: 4.4.0 - resolution: "global@npm:4.4.0" +"flat-cache@npm:^2.0.1": + version: 2.0.1 + resolution: "flat-cache@npm:2.0.1" dependencies: - min-document: ^2.19.0 - process: ^0.11.10 - checksum: 9c057557c8f5a5bcfbeb9378ba4fe2255d04679452be504608dd5f13b54edf79f7be1db1031ea06a4ec6edd3b9f5f17d2d172fb47e6c69dae57fd84b7e72b77f + flatted: ^2.0.0 + rimraf: 2.6.3 + write: 1.0.3 + checksum: 0f5e66467658039e6fcaaccb363b28f43906ba72fab7ff2a4f6fcd5b4899679e13ca46d9fc6cc48b68ac925ae93137106d4aaeb79874c13f21f87a361705f1b1 languageName: node linkType: hard -"globals@npm:^11.7.0": - version: 11.12.0 - resolution: "globals@npm:11.12.0" - checksum: 67051a45eca3db904aee189dfc7cd53c20c7d881679c93f6146ddd4c9f4ab2268e68a919df740d39c71f4445d2b38ee360fc234428baea1dbdfe68bbcb46979e +"flat-cache@npm:^3.0.4": + version: 3.0.4 + resolution: "flat-cache@npm:3.0.4" + dependencies: + flatted: ^3.1.0 + rimraf: ^3.0.2 + checksum: 4fdd10ecbcbf7d520f9040dd1340eb5dfe951e6f0ecf2252edeec03ee68d989ec8b9a20f4434270e71bcfd57800dc09b3344fca3966b2eb8f613072c7d9a2365 languageName: node linkType: hard -"globals@npm:^13.6.0, globals@npm:^13.9.0": - version: 13.11.0 - resolution: "globals@npm:13.11.0" +"flat@npm:^4.1.0": + version: 4.1.1 + resolution: "flat@npm:4.1.1" dependencies: - type-fest: ^0.20.2 - checksum: e9e5624154261a3e5344d2105a94886c5f2ca48028fa8258cd7b9119c5f00cf2909392817bb2d162c9a1a31b55d9b2c14e8f2271c45a22f77806f5b9322541cf + is-buffer: ~2.0.3 + bin: + flat: cli.js + checksum: 398be12185eb0f3c59797c3670a8c35d07020b673363175676afbaf53d6b213660e060488554cf82c25504986e1a6059bdbcc5d562e87ca3e972e8a33148e3ae languageName: node linkType: hard -"globals@npm:^9.18.0": - version: 9.18.0 - resolution: "globals@npm:9.18.0" - checksum: e9c066aecfdc5ea6f727344a4246ecc243aaf66ede3bffee10ddc0c73351794c25e727dd046090dcecd821199a63b9de6af299a6e3ba292c8b22f0a80ea32073 +"flat@npm:^5.0.2": + version: 5.0.2 + resolution: "flat@npm:5.0.2" + bin: + flat: cli.js + checksum: 12a1536ac746db74881316a181499a78ef953632ddd28050b7a3a43c62ef5462e3357c8c29d76072bb635f147f7a9a1f0c02efef6b4be28f8db62ceb3d5c7f5d languageName: node linkType: hard -"globalthis@npm:^1.0.3": - version: 1.0.3 - resolution: "globalthis@npm:1.0.3" - dependencies: - define-properties: ^1.1.3 - checksum: fbd7d760dc464c886d0196166d92e5ffb4c84d0730846d6621a39fbbc068aeeb9c8d1421ad330e94b7bca4bb4ea092f5f21f3d36077812af5d098b4dc006c998 +"flatted@npm:^2.0.0": + version: 2.0.2 + resolution: "flatted@npm:2.0.2" + checksum: 473c754db7a529e125a22057098f1a4c905ba17b8cc269c3acf77352f0ffa6304c851eb75f6a1845f74461f560e635129ca6b0b8a78fb253c65cea4de3d776f2 languageName: node linkType: hard -"globby@npm:^10.0.1": - version: 10.0.2 - resolution: "globby@npm:10.0.2" - dependencies: - "@types/glob": ^7.1.1 - array-union: ^2.1.0 - dir-glob: ^3.0.1 - fast-glob: ^3.0.3 - glob: ^7.1.3 - ignore: ^5.1.1 - merge2: ^1.2.3 - slash: ^3.0.0 - checksum: 167cd067f2cdc030db2ec43232a1e835fa06217577d545709dbf29fd21631b30ff8258705172069c855dc4d5766c3b2690834e35b936fbff01ad0329fb95a26f +"flatted@npm:^3.1.0": + version: 3.2.2 + resolution: "flatted@npm:3.2.2" + checksum: 9d5e03fd9309b9103f345cf6d0cef4fa46201baa053b0ca3d57fa489449b0bee687b7355407898f630afbb1a1286d2a6658e7e77dea3b85c3cd6c6ce2894a5c3 languageName: node linkType: hard -"globby@npm:^11.0.4": - version: 11.0.4 - resolution: "globby@npm:11.0.4" - dependencies: - array-union: ^2.1.0 - dir-glob: ^3.0.1 - fast-glob: ^3.1.1 - ignore: ^5.1.4 - merge2: ^1.3.0 - slash: ^3.0.0 - checksum: d3e02d5e459e02ffa578b45f040381c33e3c0538ed99b958f0809230c423337999867d7b0dbf752ce93c46157d3bbf154d3fff988a93ccaeb627df8e1841775b +"fmix@npm:^0.1.0": + version: 0.1.0 + resolution: "fmix@npm:0.1.0" + dependencies: + imul: ^1.0.0 + checksum: c465344d4f169eaf10d45c33949a1e7a633f09dba2ac7063ce8ae8be743df5979d708f7f24900163589f047f5194ac5fc2476177ce31175e8805adfa7b8fb7a4 languageName: node linkType: hard -"globby@npm:^11.1.0": - version: 11.1.0 - resolution: "globby@npm:11.1.0" - dependencies: - array-union: ^2.1.0 - dir-glob: ^3.0.1 - fast-glob: ^3.2.9 - ignore: ^5.2.0 - merge2: ^1.4.1 - slash: ^3.0.0 - checksum: b4be8885e0cfa018fc783792942d53926c35c50b3aefd3fdcfb9d22c627639dc26bd2327a40a0b74b074100ce95bb7187bfeae2f236856aa3de183af7a02aea6 +"follow-redirects@npm:^1.12.1, follow-redirects@npm:^1.14.8, follow-redirects@npm:^1.15.0": + version: 1.15.2 + resolution: "follow-redirects@npm:1.15.2" + peerDependenciesMeta: + debug: + optional: true + checksum: faa66059b66358ba65c234c2f2a37fcec029dc22775f35d9ad6abac56003268baf41e55f9ee645957b32c7d9f62baf1f0b906e68267276f54ec4b4c597c2b190 languageName: node linkType: hard -"gluegun@npm:5.1.2": - version: 5.1.2 - resolution: "gluegun@npm:5.1.2" - dependencies: - apisauce: ^2.1.5 - app-module-path: ^2.2.0 - cli-table3: 0.6.0 - colors: 1.4.0 - cosmiconfig: 7.0.1 - cross-spawn: 7.0.3 - ejs: 3.1.6 - enquirer: 2.3.6 - execa: 5.1.1 - fs-jetpack: 4.3.1 - lodash.camelcase: ^4.3.0 - lodash.kebabcase: ^4.1.1 - lodash.lowercase: ^4.3.0 - lodash.lowerfirst: ^4.3.1 - lodash.pad: ^4.5.1 - lodash.padend: ^4.6.1 - lodash.padstart: ^4.6.1 - lodash.repeat: ^4.1.0 - lodash.snakecase: ^4.1.1 - lodash.startcase: ^4.4.0 - lodash.trim: ^4.5.1 - lodash.trimend: ^4.5.1 - lodash.trimstart: ^4.5.1 - lodash.uppercase: ^4.3.0 - lodash.upperfirst: ^4.3.1 - ora: 4.0.2 - pluralize: ^8.0.0 - semver: 7.3.5 - which: 2.0.2 - yargs-parser: ^21.0.0 - bin: - gluegun: bin/gluegun - checksum: 2c91934b98022018a524a3be32efb3e4567905a618ccb4aca4f19207ff4b37262bc18264b306f1c82757eaab634bac6c06aacff16059b11a38deefd07b6293b6 +"follow-redirects@npm:^1.14.0": + version: 1.14.4 + resolution: "follow-redirects@npm:1.14.4" + peerDependenciesMeta: + debug: + optional: true + checksum: d4ce74cf5c6f363168b97e706b914eb9ffb6bf4d4c6d8f8330b93088d9b90e566611ddbcf0e42c8ed5fd17598dfeda1d19230d3e9d6d6c6b4d1c10ec3a0b99be languageName: node linkType: hard -"gopd@npm:^1.0.1": - version: 1.0.1 - resolution: "gopd@npm:1.0.1" - dependencies: - get-intrinsic: ^1.1.3 - checksum: a5ccfb8806e0917a94e0b3de2af2ea4979c1da920bc381667c260e00e7cafdbe844e2cb9c5bcfef4e5412e8bf73bab837285bc35c7ba73aaaf0134d4583393a6 +"follow-redirects@npm:^1.15.6": + version: 1.15.9 + resolution: "follow-redirects@npm:1.15.9" + peerDependenciesMeta: + debug: + optional: true + checksum: 859e2bacc7a54506f2bf9aacb10d165df78c8c1b0ceb8023f966621b233717dab56e8d08baadc3ad3b9db58af290413d585c999694b7c146aaf2616340c3d2a6 languageName: node linkType: hard -"got@npm:12.1.0": - version: 12.1.0 - resolution: "got@npm:12.1.0" +"for-each@npm:^0.3.3": + version: 0.3.3 + resolution: "for-each@npm:0.3.3" dependencies: - "@sindresorhus/is": ^4.6.0 - "@szmarczak/http-timer": ^5.0.1 - "@types/cacheable-request": ^6.0.2 - "@types/responselike": ^1.0.0 - cacheable-lookup: ^6.0.4 - cacheable-request: ^7.0.2 - decompress-response: ^6.0.0 - form-data-encoder: 1.7.1 - get-stream: ^6.0.1 - http2-wrapper: ^2.1.10 - lowercase-keys: ^3.0.0 - p-cancelable: ^3.0.0 - responselike: ^2.0.0 - checksum: 1cc9af6ca511338a7f1bbb0943999e6ac324ea3c7d826066c02e530b4ac41147b1a4cadad21b28c3938de82185ac99c33d64a3a4560c6e0b0b125191ba6ee619 + is-callable: ^1.1.3 + checksum: 6c48ff2bc63362319c65e2edca4a8e1e3483a2fabc72fbe7feaf8c73db94fc7861bd53bc02c8a66a0c1dd709da6b04eec42e0abdd6b40ce47305ae92a25e5d28 languageName: node linkType: hard -"got@npm:9.6.0": - version: 9.6.0 - resolution: "got@npm:9.6.0" - dependencies: - "@sindresorhus/is": ^0.14.0 - "@szmarczak/http-timer": ^1.1.2 - cacheable-request: ^6.0.0 - decompress-response: ^3.3.0 - duplexer3: ^0.1.4 - get-stream: ^4.1.0 - lowercase-keys: ^1.0.1 - mimic-response: ^1.0.1 - p-cancelable: ^1.0.0 - to-readable-stream: ^1.0.0 - url-parse-lax: ^3.0.0 - checksum: 941807bd9704bacf5eb401f0cc1212ffa1f67c6642f2d028fd75900471c221b1da2b8527f4553d2558f3faeda62ea1cf31665f8b002c6137f5de8732f07370b0 +"forever-agent@npm:~0.6.1": + version: 0.6.1 + resolution: "forever-agent@npm:0.6.1" + checksum: 766ae6e220f5fe23676bb4c6a99387cec5b7b62ceb99e10923376e27bfea72f3c3aeec2ba5f45f3f7ba65d6616965aa7c20b15002b6860833bb6e394dea546a8 languageName: node linkType: hard -"got@npm:^11.8.5": - version: 11.8.5 - resolution: "got@npm:11.8.5" - dependencies: - "@sindresorhus/is": ^4.0.0 - "@szmarczak/http-timer": ^4.0.5 - "@types/cacheable-request": ^6.0.1 - "@types/responselike": ^1.0.0 - cacheable-lookup: ^5.0.3 - cacheable-request: ^7.0.2 - decompress-response: ^6.0.0 - http2-wrapper: ^1.0.0-beta.5.2 - lowercase-keys: ^2.0.0 - p-cancelable: ^2.0.0 - responselike: ^2.0.0 - checksum: 2de8a1bbda4e9b6b2b72b2d2100bc055a59adc1740529e631f61feb44a8b9a1f9f8590941ed9da9df0090b6d6d0ed8ffee94cd9ac086ec3409b392b33440f7d2 +"form-data-encoder@npm:1.7.1": + version: 1.7.1 + resolution: "form-data-encoder@npm:1.7.1" + checksum: a2a360d5588a70d323c12a140c3db23a503a38f0a5d141af1efad579dde9f9fff2e49e5f31f378cb4631518c1ab4a826452c92f0d2869e954b6b2d77b05613e1 languageName: node linkType: hard -"graceful-fs@npm:^4.1.11, graceful-fs@npm:^4.1.2, graceful-fs@npm:^4.1.9, graceful-fs@npm:^4.2.4": - version: 4.2.10 - resolution: "graceful-fs@npm:4.2.10" - checksum: 3f109d70ae123951905d85032ebeae3c2a5a7a997430df00ea30df0e3a6c60cf6689b109654d6fdacd28810a053348c4d14642da1d075049e6be1ba5216218da +"form-data@npm:^2.2.0": + version: 2.5.1 + resolution: "form-data@npm:2.5.1" + dependencies: + asynckit: ^0.4.0 + combined-stream: ^1.0.6 + mime-types: ^2.1.12 + checksum: 5134ada56cc246b293a1ac7678dba6830000603a3979cf83ff7b2f21f2e3725202237cfb89e32bcb38a1d35727efbd3c3a22e65b42321e8ade8eec01ce755d08 languageName: node linkType: hard -"graceful-fs@npm:^4.1.6, graceful-fs@npm:^4.2.0, graceful-fs@npm:^4.2.6": - version: 4.2.8 - resolution: "graceful-fs@npm:4.2.8" - checksum: 5d224c8969ad0581d551dfabdb06882706b31af2561bd5e2034b4097e67cc27d05232849b8643866585fd0a41c7af152950f8776f4dd5579e9853733f31461c6 +"form-data@npm:^4.0.0": + version: 4.0.0 + resolution: "form-data@npm:4.0.0" + dependencies: + asynckit: ^0.4.0 + combined-stream: ^1.0.8 + mime-types: ^2.1.12 + checksum: 01135bf8675f9d5c61ff18e2e2932f719ca4de964e3be90ef4c36aacfc7b9cb2fceb5eca0b7e0190e3383fe51c5b37f4cb80b62ca06a99aaabfcfd6ac7c9328c languageName: node linkType: hard -"graphql-import-node@npm:^0.0.5": - version: 0.0.5 - resolution: "graphql-import-node@npm:0.0.5" - peerDependencies: - graphql: "*" - checksum: a9af565f3422e9e732dcf97077deff3f94b9af0d7e8001bb65a3cac607a462664f902b3603ead1626b294928c4b6302cb6aa2d49254444d465ce87c629fb842d +"form-data@npm:~2.3.2": + version: 2.3.3 + resolution: "form-data@npm:2.3.3" + dependencies: + asynckit: ^0.4.0 + combined-stream: ^1.0.6 + mime-types: ^2.1.12 + checksum: 10c1780fa13dbe1ff3100114c2ce1f9307f8be10b14bf16e103815356ff567b6be39d70fc4a40f8990b9660012dc24b0f5e1dde1b6426166eb23a445ba068ca3 languageName: node linkType: hard -"graphql@npm:15.5.0": - version: 15.5.0 - resolution: "graphql@npm:15.5.0" - checksum: 58a69f7274ae94c690bfa2517f96bbaf1327e1ca1fc46606e772ba2f7ca517adeb375346301373351e693022f448b7866163034209623d7c5315819ef8c5e7c0 +"forwarded@npm:0.2.0": + version: 0.2.0 + resolution: "forwarded@npm:0.2.0" + checksum: fd27e2394d8887ebd16a66ffc889dc983fbbd797d5d3f01087c020283c0f019a7d05ee85669383d8e0d216b116d720fc0cef2f6e9b7eb9f4c90c6e0bc7fd28e6 languageName: node linkType: hard -"graphql@npm:^16.6.0": - version: 16.7.1 - resolution: "graphql@npm:16.7.1" - checksum: c924d8428daf0e96a5ea43e9bc3cd1b6802899907d284478ac8f705c8fd233a0a51eef915f7569fb5de8acb2e85b802ccc6c85c2b157ad805c1e9adba5a299bd +"fp-ts@npm:1.19.3": + version: 1.19.3 + resolution: "fp-ts@npm:1.19.3" + checksum: eb0d4766ad561e9c5c01bfdd3d0ae589af135556921c733d26cf5289aad9f400110defdd93e6ac1d71f626697bb44d9d95ed2879c53dfd868f7cac3cf5c5553c languageName: node linkType: hard -"growl@npm:1.10.5": - version: 1.10.5 - resolution: "growl@npm:1.10.5" - checksum: 4b86685de6831cebcbb19f93870bea624afee61124b0a20c49017013987cd129e73a8c4baeca295728f41d21265e1f859d25ef36731b142ca59c655fea94bb1a +"fp-ts@npm:^1.0.0": + version: 1.19.5 + resolution: "fp-ts@npm:1.19.5" + checksum: 67d2d9c3855d211ca2592b1ef805f98b618157e7681791a776d9d0f7f3e52fcca2122ebf5bc215908c9099fad69756d40e37210cf46cb4075dae1b61efe69e40 languageName: node linkType: hard -"handlebars@npm:^4.0.1, handlebars@npm:^4.0.5": - version: 4.7.7 - resolution: "handlebars@npm:4.7.7" - dependencies: - minimist: ^1.2.5 - neo-async: ^2.6.0 - source-map: ^0.6.1 - uglify-js: ^3.1.4 - wordwrap: ^1.0.0 - dependenciesMeta: - uglify-js: - optional: true - bin: - handlebars: bin/handlebars - checksum: 1e79a43f5e18d15742977cb987923eab3e2a8f44f2d9d340982bcb69e1735ed049226e534d7c1074eaddaf37e4fb4f471a8adb71cddd5bc8cf3f894241df5cee +"fresh@npm:0.5.2": + version: 0.5.2 + resolution: "fresh@npm:0.5.2" + checksum: 13ea8b08f91e669a64e3ba3a20eb79d7ca5379a81f1ff7f4310d54e2320645503cc0c78daedc93dfb6191287295f6479544a649c64d8e41a1c0fb0c221552346 languageName: node linkType: hard -"har-schema@npm:^2.0.0": - version: 2.0.0 - resolution: "har-schema@npm:2.0.0" - checksum: d8946348f333fb09e2bf24cc4c67eabb47c8e1d1aa1c14184c7ffec1140a49ec8aa78aa93677ae452d71d5fc0fdeec20f0c8c1237291fc2bcb3f502a5d204f9b +"fs-constants@npm:^1.0.0": + version: 1.0.0 + resolution: "fs-constants@npm:1.0.0" + checksum: 18f5b718371816155849475ac36c7d0b24d39a11d91348cfcb308b4494824413e03572c403c86d3a260e049465518c4f0d5bd00f0371cdfcad6d4f30a85b350d languageName: node linkType: hard -"har-validator@npm:~5.1.3": - version: 5.1.5 - resolution: "har-validator@npm:5.1.5" +"fs-extra@npm:9.1.0, fs-extra@npm:^9.1.0": + version: 9.1.0 + resolution: "fs-extra@npm:9.1.0" dependencies: - ajv: ^6.12.3 - har-schema: ^2.0.0 - checksum: b998a7269ca560d7f219eedc53e2c664cd87d487e428ae854a6af4573fc94f182fe9d2e3b92ab968249baec7ebaf9ead69cf975c931dc2ab282ec182ee988280 + at-least-node: ^1.0.0 + graceful-fs: ^4.2.0 + jsonfile: ^6.0.1 + universalify: ^2.0.0 + checksum: ba71ba32e0faa74ab931b7a0031d1523c66a73e225de7426e275e238e312d07313d2da2d33e34a52aa406c8763ade5712eb3ec9ba4d9edce652bcacdc29e6b20 languageName: node linkType: hard -"hardhat-contract-sizer@npm:^2.1.1": - version: 2.6.1 - resolution: "hardhat-contract-sizer@npm:2.6.1" +"fs-extra@npm:^10.0.0": + version: 10.1.0 + resolution: "fs-extra@npm:10.1.0" dependencies: - chalk: ^4.0.0 - cli-table3: ^0.6.0 - peerDependencies: - hardhat: ^2.0.0 - checksum: a82ae2405a8571e8b0cd0a21dea9a10946b342f1ada04c72c9cbe28fca955f9a2b1394c70400003f388182298dc1de00e80bf56dbfa5e36833d3c93ab1f50c0c + graceful-fs: ^4.2.0 + jsonfile: ^6.0.1 + universalify: ^2.0.0 + checksum: dc94ab37096f813cc3ca12f0f1b5ad6744dfed9ed21e953d72530d103cea193c2f81584a39e9dee1bea36de5ee66805678c0dddc048e8af1427ac19c00fffc50 languageName: node linkType: hard -"hardhat-deploy-ethers@npm:^0.4.1": - version: 0.4.1 - resolution: "hardhat-deploy-ethers@npm:0.4.1" - peerDependencies: - "@nomicfoundation/hardhat-ethers": ^3.0.2 - hardhat: ^2.16.0 - hardhat-deploy: ^0.11.34 - checksum: 757b1d4ca7bdf37b87559e5aac03b6a751a06b11ba04bc23543fd794e86354872809e01089e85a21b63005b6068f7c61f8d62a6d8c1a8362ee234346b6c6f4e3 +"fs-extra@npm:^4.0.2": + version: 4.0.3 + resolution: "fs-extra@npm:4.0.3" + dependencies: + graceful-fs: ^4.1.2 + jsonfile: ^4.0.0 + universalify: ^0.1.0 + checksum: c5ae3c7043ad7187128e619c0371da01b58694c1ffa02c36fb3f5b459925d9c27c3cb1e095d9df0a34a85ca993d8b8ff6f6ecef868fd5ebb243548afa7fc0936 languageName: node linkType: hard - -"hardhat-deploy@npm:^0.11.34": - version: 0.11.34 - resolution: "hardhat-deploy@npm:0.11.34" + +"fs-extra@npm:^7.0.0, fs-extra@npm:^7.0.1": + version: 7.0.1 + resolution: "fs-extra@npm:7.0.1" dependencies: - "@ethersproject/abi": ^5.7.0 - "@ethersproject/abstract-signer": ^5.7.0 - "@ethersproject/address": ^5.7.0 - "@ethersproject/bignumber": ^5.7.0 - "@ethersproject/bytes": ^5.7.0 - "@ethersproject/constants": ^5.7.0 - "@ethersproject/contracts": ^5.7.0 - "@ethersproject/providers": ^5.7.2 - "@ethersproject/solidity": ^5.7.0 - "@ethersproject/transactions": ^5.7.0 - "@ethersproject/wallet": ^5.7.0 - "@types/qs": ^6.9.7 - axios: ^0.21.1 - chalk: ^4.1.2 - chokidar: ^3.5.2 - debug: ^4.3.2 - enquirer: ^2.3.6 - ethers: ^5.5.3 - form-data: ^4.0.0 - fs-extra: ^10.0.0 - match-all: ^1.2.6 - murmur-128: ^0.2.1 - qs: ^6.9.4 - zksync-web3: ^0.14.3 - checksum: 3c4bcd657a80e4f22c1f8bcee021e5277060849ce4180cbc721e0c2d625f2f98de8ebbfad23875d32eeaf06d88bdba06cb43ab29359cb9531e8bb7851a98ead1 + graceful-fs: ^4.1.2 + jsonfile: ^4.0.0 + universalify: ^0.1.0 + checksum: 141b9dccb23b66a66cefdd81f4cda959ff89282b1d721b98cea19ba08db3dcbe6f862f28841f3cf24bb299e0b7e6c42303908f65093cb7e201708e86ea5a8dcf languageName: node linkType: hard -"hardhat-gas-reporter@npm:^1.0.4": - version: 1.0.9 - resolution: "hardhat-gas-reporter@npm:1.0.9" +"fs-extra@npm:^8.1.0": + version: 8.1.0 + resolution: "fs-extra@npm:8.1.0" dependencies: - array-uniq: 1.0.3 - eth-gas-reporter: ^0.2.25 - sha1: ^1.1.1 - peerDependencies: - hardhat: ^2.0.2 - checksum: 77f8f8d085ff3d9d7787f0227e5355e1800f7d6707bc70171e0567bf69706703ae7f6f53dce1be1d409e7e71e3629a434c94b546bdbbc1e4c1af47cd5d0c6776 + graceful-fs: ^4.2.0 + jsonfile: ^4.0.0 + universalify: ^0.1.0 + checksum: bf44f0e6cea59d5ce071bba4c43ca76d216f89e402dc6285c128abc0902e9b8525135aa808adad72c9d5d218e9f4bcc63962815529ff2f684ad532172a284880 languageName: node linkType: hard -"hardhat-shorthand@npm:^1.0.0": - version: 1.0.0 - resolution: "hardhat-shorthand@npm:1.0.0" +"fs-jetpack@npm:4.3.1": + version: 4.3.1 + resolution: "fs-jetpack@npm:4.3.1" dependencies: - "@fvictorio/tabtab": ^0.0.3 - debug: ^4.1.1 - semver: ^6.3.0 - bin: - hardhat-completion: dist/src/completion.js - hh: dist/src/index.js - checksum: df9caf38881ed72f954e4ed5703826923d74c8fe02974bf62e7547478200177f8cbf7e4aa96f55e9be638f07719dcf8f73e2e88a8643fbff6de3e8f7b56c58f9 + minimatch: ^3.0.2 + rimraf: ^2.6.3 + checksum: ffe90946ec250c6042569faa2ec7753594779ca0e8a72eea0b76b82574542c50d580974f54c5d6885f44f5719ece173be778cf82dc50ad90f43dab043f4061c9 languageName: node linkType: hard -"hardhat@npm:^2.16.1": - version: 2.16.1 - resolution: "hardhat@npm:2.16.1" +"fs-minipass@npm:^1.2.7": + version: 1.2.7 + resolution: "fs-minipass@npm:1.2.7" dependencies: - "@ethersproject/abi": ^5.1.2 - "@metamask/eth-sig-util": ^4.0.0 - "@nomicfoundation/ethereumjs-block": 5.0.1 - "@nomicfoundation/ethereumjs-blockchain": 7.0.1 - "@nomicfoundation/ethereumjs-common": 4.0.1 - "@nomicfoundation/ethereumjs-evm": 2.0.1 - "@nomicfoundation/ethereumjs-rlp": 5.0.1 - "@nomicfoundation/ethereumjs-statemanager": 2.0.1 - "@nomicfoundation/ethereumjs-trie": 6.0.1 - "@nomicfoundation/ethereumjs-tx": 5.0.1 - "@nomicfoundation/ethereumjs-util": 9.0.1 - "@nomicfoundation/ethereumjs-vm": 7.0.1 - "@nomicfoundation/solidity-analyzer": ^0.1.0 - "@sentry/node": ^5.18.1 - "@types/bn.js": ^5.1.0 - "@types/lru-cache": ^5.1.0 - abort-controller: ^3.0.0 - adm-zip: ^0.4.16 - aggregate-error: ^3.0.0 - ansi-escapes: ^4.3.0 - chalk: ^2.4.2 - chokidar: ^3.4.0 - ci-info: ^2.0.0 - debug: ^4.1.1 - enquirer: ^2.3.0 - env-paths: ^2.2.0 - ethereum-cryptography: ^1.0.3 - ethereumjs-abi: ^0.6.8 - find-up: ^2.1.0 - fp-ts: 1.19.3 - fs-extra: ^7.0.1 - glob: 7.2.0 - immutable: ^4.0.0-rc.12 - io-ts: 1.10.4 - keccak: ^3.0.2 - lodash: ^4.17.11 - mnemonist: ^0.38.0 - mocha: ^10.0.0 - p-map: ^4.0.0 - raw-body: ^2.4.1 - resolve: 1.17.0 - semver: ^6.3.0 - solc: 0.7.3 - source-map-support: ^0.5.13 - stacktrace-parser: ^0.1.10 - tsort: 0.0.1 - undici: ^5.14.0 - uuid: ^8.3.2 - ws: ^7.4.6 - peerDependencies: - ts-node: "*" - typescript: "*" - peerDependenciesMeta: - ts-node: - optional: true - typescript: - optional: true - bin: - hardhat: internal/cli/bootstrap.js - checksum: 32508ab6463efd796e8805150c182a9b974fcec8e4ab362a95f8bab2b4baf24c4feb48bbee1f3a7165a934f5257e1d3fcfea5764f261404aec23a88066341e48 + minipass: ^2.6.0 + checksum: 40fd46a2b5dcb74b3a580269f9a0c36f9098c2ebd22cef2e1a004f375b7b665c11f1507ec3f66ee6efab5664109f72d0a74ea19c3370842214c3da5168d6fdd7 languageName: node linkType: hard -"has-ansi@npm:^2.0.0": - version: 2.0.0 - resolution: "has-ansi@npm:2.0.0" +"fs-minipass@npm:^2.0.0": + version: 2.1.0 + resolution: "fs-minipass@npm:2.1.0" dependencies: - ansi-regex: ^2.0.0 - checksum: 1b51daa0214440db171ff359d0a2d17bc20061164c57e76234f614c91dbd2a79ddd68dfc8ee73629366f7be45a6df5f2ea9de83f52e1ca24433f2cc78c35d8ec + minipass: ^3.0.0 + checksum: 1b8d128dae2ac6cc94230cc5ead341ba3e0efaef82dab46a33d171c044caaa6ca001364178d42069b2809c35a1c3c35079a32107c770e9ffab3901b59af8c8b1 languageName: node linkType: hard -"has-bigints@npm:^1.0.1": - version: 1.0.1 - resolution: "has-bigints@npm:1.0.1" - checksum: 44ab55868174470065d2e0f8f6def1c990d12b82162a8803c679699fa8a39f966e336f2a33c185092fe8aea7e8bf2e85f1c26add5f29d98f2318bd270096b183 +"fs-promise@npm:^0.3.1": + version: 0.3.1 + resolution: "fs-promise@npm:0.3.1" + dependencies: + any-promise: ~0.1.0 + checksum: b67515925e695fbacc24d081567f2b2efe23e1936248916d619a5f545f5e320074d4164ce06c79e7f984fb0ee4878712b36bb9016f11435618e25b27817095a1 languageName: node linkType: hard -"has-bigints@npm:^1.0.2": - version: 1.0.2 - resolution: "has-bigints@npm:1.0.2" - checksum: 390e31e7be7e5c6fe68b81babb73dfc35d413604d7ee5f56da101417027a4b4ce6a27e46eff97ad040c835b5d228676eae99a9b5c3bc0e23c8e81a49241ff45b +"fs-readdir-recursive@npm:^1.1.0": + version: 1.1.0 + resolution: "fs-readdir-recursive@npm:1.1.0" + checksum: 29d50f3d2128391c7fc9fd051c8b7ea45bcc8aa84daf31ef52b17218e20bfd2bd34d02382742801954cc8d1905832b68227f6b680a666ce525d8b6b75068ad1e languageName: node linkType: hard -"has-flag@npm:^1.0.0": +"fs.realpath@npm:^1.0.0": version: 1.0.0 - resolution: "has-flag@npm:1.0.0" - checksum: ce3f8ae978e70f16e4bbe17d3f0f6d6c0a3dd3b62a23f97c91d0fda9ed8e305e13baf95cc5bee4463b9f25ac9f5255de113165c5fb285e01b8065b2ac079b301 + resolution: "fs.realpath@npm:1.0.0" + checksum: 99ddea01a7e75aa276c250a04eedeffe5662bce66c65c07164ad6264f9de18fb21be9433ead460e54cff20e31721c811f4fb5d70591799df5f85dce6d6746fd0 languageName: node linkType: hard -"has-flag@npm:^3.0.0": - version: 3.0.0 - resolution: "has-flag@npm:3.0.0" - checksum: 4a15638b454bf086c8148979aae044dd6e39d63904cd452d970374fa6a87623423da485dfb814e7be882e05c096a7ccf1ebd48e7e7501d0208d8384ff4dea73b +"fsevents@npm:~2.1.1": + version: 2.1.3 + resolution: "fsevents@npm:2.1.3" + dependencies: + node-gyp: latest + checksum: b5ec0516b44d75b60af5c01ff80a80cd995d175e4640d2a92fbabd02991dd664d76b241b65feef0775c23d531c3c74742c0fbacd6205af812a9c3cef59f04292 + conditions: os=darwin languageName: node linkType: hard -"has-flag@npm:^4.0.0": - version: 4.0.0 - resolution: "has-flag@npm:4.0.0" - checksum: 261a1357037ead75e338156b1f9452c016a37dcd3283a972a30d9e4a87441ba372c8b81f818cd0fbcd9c0354b4ae7e18b9e1afa1971164aef6d18c2b6095a8ad +"fsevents@npm:~2.3.2": + version: 2.3.2 + resolution: "fsevents@npm:2.3.2" + dependencies: + node-gyp: latest + checksum: 97ade64e75091afee5265e6956cb72ba34db7819b4c3e94c431d4be2b19b8bb7a2d4116da417950c3425f17c8fe693d25e20212cac583ac1521ad066b77ae31f + conditions: os=darwin languageName: node linkType: hard -"has-property-descriptors@npm:^1.0.0": - version: 1.0.0 - resolution: "has-property-descriptors@npm:1.0.0" +"fsevents@patch:fsevents@~2.1.1#~builtin": + version: 2.1.3 + resolution: "fsevents@patch:fsevents@npm%3A2.1.3#~builtin::version=2.1.3&hash=31d12a" dependencies: - get-intrinsic: ^1.1.1 - checksum: a6d3f0a266d0294d972e354782e872e2fe1b6495b321e6ef678c9b7a06a40408a6891817350c62e752adced73a94ac903c54734fee05bf65b1905ee1368194bb + node-gyp: latest + conditions: os=darwin languageName: node linkType: hard -"has-proto@npm:^1.0.1": - version: 1.0.1 - resolution: "has-proto@npm:1.0.1" - checksum: febc5b5b531de8022806ad7407935e2135f1cc9e64636c3916c6842bd7995994ca3b29871ecd7954bd35f9e2986c17b3b227880484d22259e2f8e6ce63fd383e +"fsevents@patch:fsevents@~2.3.2#~builtin": + version: 2.3.2 + resolution: "fsevents@patch:fsevents@npm%3A2.3.2#~builtin::version=2.3.2&hash=df0bf1" + dependencies: + node-gyp: latest + conditions: os=darwin languageName: node linkType: hard -"has-symbols@npm:^1.0.0, has-symbols@npm:^1.0.3": - version: 1.0.3 - resolution: "has-symbols@npm:1.0.3" - checksum: a054c40c631c0d5741a8285010a0777ea0c068f99ed43e5d6eb12972da223f8af553a455132fdb0801bdcfa0e0f443c0c03a68d8555aa529b3144b446c3f2410 +"function-bind@npm:^1.1.1": + version: 1.1.1 + resolution: "function-bind@npm:1.1.1" + checksum: b32fbaebb3f8ec4969f033073b43f5c8befbb58f1a79e12f1d7490358150359ebd92f49e72ff0144f65f2c48ea2a605bff2d07965f548f6474fd8efd95bf361a languageName: node linkType: hard -"has-symbols@npm:^1.0.1, has-symbols@npm:^1.0.2": - version: 1.0.2 - resolution: "has-symbols@npm:1.0.2" - checksum: 2309c426071731be792b5be43b3da6fb4ed7cbe8a9a6bcfca1862587709f01b33d575ce8f5c264c1eaad09fca2f9a8208c0a2be156232629daa2dd0c0740976b +"function.prototype.name@npm:^1.1.5": + version: 1.1.5 + resolution: "function.prototype.name@npm:1.1.5" + dependencies: + call-bind: ^1.0.2 + define-properties: ^1.1.3 + es-abstract: ^1.19.0 + functions-have-names: ^1.2.2 + checksum: acd21d733a9b649c2c442f067567743214af5fa248dbeee69d8278ce7df3329ea5abac572be9f7470b4ec1cd4d8f1040e3c5caccf98ebf2bf861a0deab735c27 languageName: node linkType: hard -"has-tostringtag@npm:^1.0.0": - version: 1.0.0 - resolution: "has-tostringtag@npm:1.0.0" +"function.prototype.name@npm:^1.1.6": + version: 1.1.6 + resolution: "function.prototype.name@npm:1.1.6" dependencies: - has-symbols: ^1.0.2 - checksum: cc12eb28cb6ae22369ebaad3a8ab0799ed61270991be88f208d508076a1e99abe4198c965935ce85ea90b60c94ddda73693b0920b58e7ead048b4a391b502c1c + call-bind: ^1.0.2 + define-properties: ^1.2.0 + es-abstract: ^1.22.1 + functions-have-names: ^1.2.3 + checksum: 7a3f9bd98adab09a07f6e1f03da03d3f7c26abbdeaeee15223f6c04a9fb5674792bdf5e689dac19b97ac71de6aad2027ba3048a9b883aa1b3173eed6ab07f479 languageName: node linkType: hard -"has-unicode@npm:^2.0.0": - version: 2.0.1 - resolution: "has-unicode@npm:2.0.1" - checksum: 1eab07a7436512db0be40a710b29b5dc21fa04880b7f63c9980b706683127e3c1b57cb80ea96d47991bdae2dfe479604f6a1ba410106ee1046a41d1bd0814400 +"functional-red-black-tree@npm:^1.0.1": + version: 1.0.1 + resolution: "functional-red-black-tree@npm:1.0.1" + checksum: ca6c170f37640e2d94297da8bb4bf27a1d12bea3e00e6a3e007fd7aa32e37e000f5772acf941b4e4f3cf1c95c3752033d0c509af157ad8f526e7f00723b9eb9f languageName: node linkType: hard -"has-value@npm:^0.3.1": - version: 0.3.1 - resolution: "has-value@npm:0.3.1" - dependencies: - get-value: ^2.0.3 - has-values: ^0.1.4 - isobject: ^2.0.0 - checksum: 29e2a1e6571dad83451b769c7ce032fce6009f65bccace07c2962d3ad4d5530b6743d8f3229e4ecf3ea8e905d23a752c5f7089100c1f3162039fa6dc3976558f +"functions-have-names@npm:^1.2.2, functions-have-names@npm:^1.2.3": + version: 1.2.3 + resolution: "functions-have-names@npm:1.2.3" + checksum: c3f1f5ba20f4e962efb71344ce0a40722163e85bee2101ce25f88214e78182d2d2476aa85ef37950c579eb6cf6ee811c17b3101bb84004bb75655f3e33f3fdb5 languageName: node linkType: hard -"has-value@npm:^1.0.0": - version: 1.0.0 - resolution: "has-value@npm:1.0.0" +"gauge@npm:~2.7.3": + version: 2.7.4 + resolution: "gauge@npm:2.7.4" dependencies: - get-value: ^2.0.6 - has-values: ^1.0.0 - isobject: ^3.0.0 - checksum: b9421d354e44f03d3272ac39fd49f804f19bc1e4fa3ceef7745df43d6b402053f828445c03226b21d7d934a21ac9cf4bc569396dc312f496ddff873197bbd847 + aproba: ^1.0.3 + console-control-strings: ^1.0.0 + has-unicode: ^2.0.0 + object-assign: ^4.1.0 + signal-exit: ^3.0.0 + string-width: ^1.0.1 + strip-ansi: ^3.0.1 + wide-align: ^1.1.0 + checksum: a89b53cee65579b46832e050b5f3a79a832cc422c190de79c6b8e2e15296ab92faddde6ddf2d376875cbba2b043efa99b9e1ed8124e7365f61b04e3cee9d40ee languageName: node linkType: hard -"has-values@npm:^0.1.4": - version: 0.1.4 - resolution: "has-values@npm:0.1.4" - checksum: ab1c4bcaf811ccd1856c11cfe90e62fca9e2b026ebe474233a3d282d8d67e3b59ed85b622c7673bac3db198cb98bd1da2b39300a2f98e453729b115350af49bc +"get-caller-file@npm:^2.0.1, get-caller-file@npm:^2.0.5": + version: 2.0.5 + resolution: "get-caller-file@npm:2.0.5" + checksum: b9769a836d2a98c3ee734a88ba712e62703f1df31b94b784762c433c27a386dd6029ff55c2a920c392e33657d80191edbf18c61487e198844844516f843496b9 languageName: node linkType: hard -"has-values@npm:^1.0.0": - version: 1.0.0 - resolution: "has-values@npm:1.0.0" - dependencies: - is-number: ^3.0.0 - kind-of: ^4.0.0 - checksum: 77e6693f732b5e4cf6c38dfe85fdcefad0fab011af74995c3e83863fabf5e3a836f406d83565816baa0bc0a523c9410db8b990fe977074d61aeb6d8f4fcffa11 +"get-func-name@npm:^2.0.0": + version: 2.0.0 + resolution: "get-func-name@npm:2.0.0" + checksum: 8d82e69f3e7fab9e27c547945dfe5cc0c57fc0adf08ce135dddb01081d75684a03e7a0487466f478872b341d52ac763ae49e660d01ab83741f74932085f693c3 languageName: node linkType: hard -"has@npm:^1.0.3, has@npm:~1.0.3": - version: 1.0.3 - resolution: "has@npm:1.0.3" +"get-intrinsic@npm:^1.0.2, get-intrinsic@npm:^1.1.0, get-intrinsic@npm:^1.1.1": + version: 1.1.1 + resolution: "get-intrinsic@npm:1.1.1" dependencies: function-bind: ^1.1.1 - checksum: b9ad53d53be4af90ce5d1c38331e712522417d017d5ef1ebd0507e07c2fbad8686fffb8e12ddecd4c39ca9b9b47431afbb975b8abf7f3c3b82c98e9aad052792 - languageName: node - linkType: hard - -"hash-base@npm:^3.0.0": - version: 3.1.0 - resolution: "hash-base@npm:3.1.0" - dependencies: - inherits: ^2.0.4 - readable-stream: ^3.6.0 - safe-buffer: ^5.2.0 - checksum: 26b7e97ac3de13cb23fc3145e7e3450b0530274a9562144fc2bf5c1e2983afd0e09ed7cc3b20974ba66039fad316db463da80eb452e7373e780cbee9a0d2f2dc + has: ^1.0.3 + has-symbols: ^1.0.1 + checksum: a9fe2ca8fa3f07f9b0d30fb202bcd01f3d9b9b6b732452e79c48e79f7d6d8d003af3f9e38514250e3553fdc83c61650851cb6870832ac89deaaceb08e3721a17 languageName: node linkType: hard -"hash.js@npm:1.1.3": +"get-intrinsic@npm:^1.1.3": version: 1.1.3 - resolution: "hash.js@npm:1.1.3" + resolution: "get-intrinsic@npm:1.1.3" dependencies: - inherits: ^2.0.3 - minimalistic-assert: ^1.0.0 - checksum: 93de6f178bf71feee38f66868a57ecb5602d937c1ccd69951b0bfec1488813b6afdbb4a81ddb2c62488c419b4a35af352298b006f14c9cfbf5b872c4191b657f + function-bind: ^1.1.1 + has: ^1.0.3 + has-symbols: ^1.0.3 + checksum: 152d79e87251d536cf880ba75cfc3d6c6c50e12b3a64e1ea960e73a3752b47c69f46034456eae1b0894359ce3bc64c55c186f2811f8a788b75b638b06fab228a languageName: node linkType: hard -"hash.js@npm:1.1.7, hash.js@npm:^1.0.0, hash.js@npm:^1.0.3, hash.js@npm:^1.1.7": - version: 1.1.7 - resolution: "hash.js@npm:1.1.7" +"get-intrinsic@npm:^1.2.0, get-intrinsic@npm:^1.2.1": + version: 1.2.1 + resolution: "get-intrinsic@npm:1.2.1" dependencies: - inherits: ^2.0.3 - minimalistic-assert: ^1.0.1 - checksum: e350096e659c62422b85fa508e4b3669017311aa4c49b74f19f8e1bc7f3a54a584fdfd45326d4964d6011f2b2d882e38bea775a96046f2a61b7779a979629d8f + function-bind: ^1.1.1 + has: ^1.0.3 + has-proto: ^1.0.1 + has-symbols: ^1.0.3 + checksum: 5b61d88552c24b0cf6fa2d1b3bc5459d7306f699de060d76442cce49a4721f52b8c560a33ab392cf5575b7810277d54ded9d4d39a1ea61855619ebc005aa7e5f languageName: node linkType: hard -"hbs-cli@npm:^1.4.1": - version: 1.4.1 - resolution: "hbs-cli@npm:1.4.1" - dependencies: - babel-runtime: ^5.8.34 - debug: ^2.2.0 - fs-promise: ^0.3.1 - get-stdin: ^8.0.0 - glob-promise: ^1.0.4 - handlebars: ^4.0.5 - lodash.merge: ^4.6.2 - minimist: ^1.2.0 - mkdirp-then: ^1.2.0 - resolve: ^1.1.6 - bin: - hbs: lib/index.js - checksum: ecdeb5802e48208bfadb6912ebfb91d1cc534416745779e5bb2f3c5ece2df9300ec668fa324edd25e88d547e89c0f1016d7dca769475d521f97eaf2f11c9844a +"get-iterator@npm:^1.0.2": + version: 1.0.2 + resolution: "get-iterator@npm:1.0.2" + checksum: 4a819aa91ecb61f4fd507bd62e3468d55f642f06011f944c381a739a21f685c36a37feb9324c8971e7c0fc70ca172066c45874fa2d1dcdf4b4fb8e43f16058c2 languageName: node linkType: hard -"he@npm:1.2.0": - version: 1.2.0 - resolution: "he@npm:1.2.0" - bin: - he: bin/he - checksum: 3d4d6babccccd79c5c5a3f929a68af33360d6445587d628087f39a965079d84f18ce9c3d3f917ee1e3978916fc833bb8b29377c3b403f919426f91bc6965e7a7 +"get-package-type@npm:^0.1.0": + version: 0.1.0 + resolution: "get-package-type@npm:0.1.0" + checksum: bba0811116d11e56d702682ddef7c73ba3481f114590e705fc549f4d868972263896af313c57a25c076e3c0d567e11d919a64ba1b30c879be985fc9d44f96148 languageName: node linkType: hard -"heap@npm:0.2.6": - version: 0.2.6 - resolution: "heap@npm:0.2.6" - checksum: 1291b9b9efb5090d01c6d04a89c91ca6e0e0eb7f3694d8254f7a5effcc5ab9249bc3d16767b276645ffe86d9b2bbd82ed977f8988f55375e9f2a2c80647ebbdc +"get-port@npm:^3.1.0": + version: 3.2.0 + resolution: "get-port@npm:3.2.0" + checksum: 31f530326569683ac4b7452eb7573c40e9dbe52aec14d80745c35475261e6389160da153d5b8ae911150b4ce99003472b30c69ba5be0cedeaa7865b95542d168 languageName: node linkType: hard -"hmac-drbg@npm:^1.0.1": - version: 1.0.1 - resolution: "hmac-drbg@npm:1.0.1" - dependencies: - hash.js: ^1.0.3 - minimalistic-assert: ^1.0.0 - minimalistic-crypto-utils: ^1.0.1 - checksum: bd30b6a68d7f22d63f10e1888aee497d7c2c5c0bb469e66bbdac99f143904d1dfe95f8131f95b3e86c86dd239963c9d972fcbe147e7cffa00e55d18585c43fe0 +"get-stdin@npm:^8.0.0": + version: 8.0.0 + resolution: "get-stdin@npm:8.0.0" + checksum: 40128b6cd25781ddbd233344f1a1e4006d4284906191ed0a7d55ec2c1a3e44d650f280b2c9eeab79c03ac3037da80257476c0e4e5af38ddfb902d6ff06282d77 languageName: node linkType: hard -"home-or-tmp@npm:^2.0.0": - version: 2.0.0 - resolution: "home-or-tmp@npm:2.0.0" +"get-stream@npm:^5.1.0": + version: 5.2.0 + resolution: "get-stream@npm:5.2.0" dependencies: - os-homedir: ^1.0.0 - os-tmpdir: ^1.0.1 - checksum: b783c6ffd22f716d82f53e8c781cbe49bc9f4109a89ea86a27951e54c0bd335caf06bd828be2958cd9f4681986df1739558ae786abda6298cdd6d3edc2c362f1 + pump: ^3.0.0 + checksum: 8bc1a23174a06b2b4ce600df38d6c98d2ef6d84e020c1ddad632ad75bac4e092eeb40e4c09e0761c35fc2dbc5e7fff5dab5e763a383582c4a167dd69a905bd12 languageName: node linkType: hard -"hosted-git-info@npm:^2.1.4, hosted-git-info@npm:^2.6.0": - version: 2.8.9 - resolution: "hosted-git-info@npm:2.8.9" - checksum: c955394bdab888a1e9bb10eb33029e0f7ce5a2ac7b3f158099dc8c486c99e73809dca609f5694b223920ca2174db33d32b12f9a2a47141dc59607c29da5a62dd +"get-stream@npm:^6.0.0, get-stream@npm:^6.0.1": + version: 6.0.1 + resolution: "get-stream@npm:6.0.1" + checksum: e04ecece32c92eebf5b8c940f51468cd53554dcbb0ea725b2748be583c9523d00128137966afce410b9b051eb2ef16d657cd2b120ca8edafcf5a65e81af63cad languageName: node linkType: hard -"http-basic@npm:^8.1.1": - version: 8.1.3 - resolution: "http-basic@npm:8.1.3" +"get-symbol-description@npm:^1.0.0": + version: 1.0.0 + resolution: "get-symbol-description@npm:1.0.0" dependencies: - caseless: ^0.12.0 - concat-stream: ^1.6.2 - http-response-object: ^3.0.1 - parse-cache-control: ^1.0.1 - checksum: 7df5dc4d4b6eb8cc3beaa77f8e5c3074288ec3835abd83c85e5bb66d8a95a0ef97664d862caf5e225698cb795f78f9a5abd0d39404e5356ccd3e5e10c87936a5 - languageName: node - linkType: hard - -"http-cache-semantics@npm:^4.0.0, http-cache-semantics@npm:^4.1.0": - version: 4.1.0 - resolution: "http-cache-semantics@npm:4.1.0" - checksum: 974de94a81c5474be07f269f9fd8383e92ebb5a448208223bfb39e172a9dbc26feff250192ecc23b9593b3f92098e010406b0f24bd4d588d631f80214648ed42 + call-bind: ^1.0.2 + get-intrinsic: ^1.1.1 + checksum: 9ceff8fe968f9270a37a1f73bf3f1f7bda69ca80f4f80850670e0e7b9444ff99323f7ac52f96567f8b5f5fbe7ac717a0d81d3407c7313e82810c6199446a5247 languageName: node linkType: hard -"http-errors@npm:2.0.0": - version: 2.0.0 - resolution: "http-errors@npm:2.0.0" +"getpass@npm:^0.1.1": + version: 0.1.7 + resolution: "getpass@npm:0.1.7" dependencies: - depd: 2.0.0 - inherits: 2.0.4 - setprototypeof: 1.2.0 - statuses: 2.0.1 - toidentifier: 1.0.1 - checksum: 9b0a3782665c52ce9dc658a0d1560bcb0214ba5699e4ea15aefb2a496e2ca83db03ebc42e1cce4ac1f413e4e0d2d736a3fd755772c556a9a06853ba2a0b7d920 - languageName: node - linkType: hard - -"http-https@npm:^1.0.0": - version: 1.0.0 - resolution: "http-https@npm:1.0.0" - checksum: 82fc4d2e512c64b35680944d1ae13e68220acfa05b06329832e271fd199c5c7fcff1f53fc1f91a1cd65a737ee4de14004dd3ba9a73cce33da970940c6e6ca774 + assert-plus: ^1.0.0 + checksum: ab18d55661db264e3eac6012c2d3daeafaab7a501c035ae0ccb193c3c23e9849c6e29b6ac762b9c2adae460266f925d55a3a2a3a3c8b94be2f222df94d70c046 languageName: node linkType: hard -"http-proxy-agent@npm:^4.0.1": - version: 4.0.1 - resolution: "http-proxy-agent@npm:4.0.1" +"ghost-testrpc@npm:^0.0.2": + version: 0.0.2 + resolution: "ghost-testrpc@npm:0.0.2" dependencies: - "@tootallnate/once": 1 - agent-base: 6 - debug: 4 - checksum: c6a5da5a1929416b6bbdf77b1aca13888013fe7eb9d59fc292e25d18e041bb154a8dfada58e223fc7b76b9b2d155a87e92e608235201f77d34aa258707963a82 + chalk: ^2.4.2 + node-emoji: ^1.10.0 + bin: + testrpc-sc: ./index.js + checksum: 3f86326d32f5e96c9356381837edde7dd0f23dcb7223aa73e02816256b84703cb76ce922987054a05b65963326088e99a4aa142d4b467ddda7c28547ed915d6d languageName: node linkType: hard -"http-response-object@npm:^3.0.1": - version: 3.0.2 - resolution: "http-response-object@npm:3.0.2" - dependencies: - "@types/node": ^10.0.3 - checksum: 6cbdcb4ce7b27c9158a131b772c903ed54add2ba831e29cc165e91c3969fa6f8105ddf924aac5b954b534ad15a1ae697b693331b2be5281ee24d79aae20c3264 +"github-from-package@npm:0.0.0": + version: 0.0.0 + resolution: "github-from-package@npm:0.0.0" + checksum: 14e448192a35c1e42efee94c9d01a10f42fe790375891a24b25261246ce9336ab9df5d274585aedd4568f7922246c2a78b8a8cd2571bfe99c693a9718e7dd0e3 languageName: node linkType: hard -"http-signature@npm:~1.2.0": - version: 1.2.0 - resolution: "http-signature@npm:1.2.0" +"glob-parent@npm:^5.1.2, glob-parent@npm:~5.1.0, glob-parent@npm:~5.1.2": + version: 5.1.2 + resolution: "glob-parent@npm:5.1.2" dependencies: - assert-plus: ^1.0.0 - jsprim: ^1.2.2 - sshpk: ^1.7.0 - checksum: 3324598712266a9683585bb84a75dec4fd550567d5e0dd4a0fff6ff3f74348793404d3eeac4918fa0902c810eeee1a86419e4a2e92a164132dfe6b26743fb47c + is-glob: ^4.0.1 + checksum: f4f2bfe2425296e8a47e36864e4f42be38a996db40420fe434565e4480e3322f18eb37589617a98640c5dc8fdec1a387007ee18dbb1f3f5553409c34d17f425e languageName: node linkType: hard -"http2-wrapper@npm:^1.0.0-beta.5.2": - version: 1.0.3 - resolution: "http2-wrapper@npm:1.0.3" +"glob-parent@npm:^6.0.2": + version: 6.0.2 + resolution: "glob-parent@npm:6.0.2" dependencies: - quick-lru: ^5.1.1 - resolve-alpn: ^1.0.0 - checksum: 74160b862ec699e3f859739101ff592d52ce1cb207b7950295bf7962e4aa1597ef709b4292c673bece9c9b300efad0559fc86c71b1409c7a1e02b7229456003e + is-glob: ^4.0.3 + checksum: c13ee97978bef4f55106b71e66428eb1512e71a7466ba49025fc2aec59a5bfb0954d5abd58fc5ee6c9b076eef4e1f6d3375c2e964b88466ca390da4419a786a8 languageName: node linkType: hard -"http2-wrapper@npm:^2.1.10": - version: 2.1.11 - resolution: "http2-wrapper@npm:2.1.11" +"glob-promise@npm:^1.0.4": + version: 1.0.6 + resolution: "glob-promise@npm:1.0.6" dependencies: - quick-lru: ^5.1.1 - resolve-alpn: ^1.2.0 - checksum: 5da05aa2c77226ac9cc82c616383f59c8f31b79897b02ecbe44b09714be1fca1f21bb184e672a669ca2830eefea4edac5f07e71c00cb5a8c5afec8e5a20cfaf7 + glob: "*" + checksum: 650a663697c6cb03caf32c4ab9200ca5b6e796f051af52f42a2c491b98da4a856f6102815253207b2fd3ebe114db867b11b19f1aaa7e4c72040e52170c7d5090 languageName: node linkType: hard -"https-proxy-agent@npm:^5.0.0": - version: 5.0.0 - resolution: "https-proxy-agent@npm:5.0.0" +"glob@npm:*": + version: 9.2.1 + resolution: "glob@npm:9.2.1" dependencies: - agent-base: 6 - debug: 4 - checksum: 165bfb090bd26d47693597661298006841ab733d0c7383a8cb2f17373387a94c903a3ac687090aa739de05e379ab6f868bae84ab4eac288ad85c328cd1ec9e53 - languageName: node - linkType: hard - -"human-signals@npm:^2.1.0": - version: 2.1.0 - resolution: "human-signals@npm:2.1.0" - checksum: b87fd89fce72391625271454e70f67fe405277415b48bcc0117ca73d31fa23a4241787afdc8d67f5a116cf37258c052f59ea82daffa72364d61351423848e3b8 + fs.realpath: ^1.0.0 + minimatch: ^7.4.1 + minipass: ^4.2.4 + path-scurry: ^1.6.1 + checksum: ef9b1c32491e6b532bdd0d2abcc3c9f48e83446609e11285869156982fc5a756dfbaa6f59f797712343bd1e22500ac15708692806633653fde4ef67c85e2aab7 languageName: node linkType: hard -"humanize-ms@npm:^1.2.1": - version: 1.2.1 - resolution: "humanize-ms@npm:1.2.1" +"glob@npm:7.1.3": + version: 7.1.3 + resolution: "glob@npm:7.1.3" dependencies: - ms: ^2.0.0 - checksum: 9c7a74a2827f9294c009266c82031030eae811ca87b0da3dceb8d6071b9bde22c9f3daef0469c3c533cc67a97d8a167cd9fc0389350e5f415f61a79b171ded16 + fs.realpath: ^1.0.0 + inflight: ^1.0.4 + inherits: 2 + minimatch: ^3.0.4 + once: ^1.3.0 + path-is-absolute: ^1.0.0 + checksum: d72a834a393948d6c4a5cacc6a29fe5fe190e1cd134e55dfba09aee0be6fe15be343e96d8ec43558ab67ff8af28e4420c7f63a4d4db1c779e515015e9c318616 languageName: node linkType: hard -"husky@npm:^8.0.1": - version: 8.0.1 - resolution: "husky@npm:8.0.1" - bin: - husky: lib/bin.js - checksum: 943a73a13d0201318fd30e83d299bb81d866bd245b69e6277804c3b462638dc1921694cb94c2b8c920a4a187060f7d6058d3365152865406352e934c5fff70dc +"glob@npm:7.1.7": + version: 7.1.7 + resolution: "glob@npm:7.1.7" + dependencies: + fs.realpath: ^1.0.0 + inflight: ^1.0.4 + inherits: 2 + minimatch: ^3.0.4 + once: ^1.3.0 + path-is-absolute: ^1.0.0 + checksum: b61f48973bbdcf5159997b0874a2165db572b368b931135832599875919c237fc05c12984e38fe828e69aa8a921eb0e8a4997266211c517c9cfaae8a93988bb8 languageName: node linkType: hard -"hyperlinker@npm:^1.0.0": - version: 1.0.0 - resolution: "hyperlinker@npm:1.0.0" - checksum: f6d020ac552e9d048668206c805a737262b4c395546c773cceea3bc45252c46b4fa6eeb67c5896499dad00d21cb2f20f89fdd480a4529cfa3d012da2957162f9 +"glob@npm:7.2.0, glob@npm:^7.0.0, glob@npm:^7.1.3, glob@npm:^7.1.4": + version: 7.2.0 + resolution: "glob@npm:7.2.0" + dependencies: + fs.realpath: ^1.0.0 + inflight: ^1.0.4 + inherits: 2 + minimatch: ^3.0.4 + once: ^1.3.0 + path-is-absolute: ^1.0.0 + checksum: 78a8ea942331f08ed2e055cb5b9e40fe6f46f579d7fd3d694f3412fe5db23223d29b7fee1575440202e9a7ff9a72ab106a39fee39934c7bedafe5e5f8ae20134 languageName: node linkType: hard -"iconv-lite@npm:0.4.24, iconv-lite@npm:^0.4.24": - version: 0.4.24 - resolution: "iconv-lite@npm:0.4.24" +"glob@npm:9.3.5": + version: 9.3.5 + resolution: "glob@npm:9.3.5" dependencies: - safer-buffer: ">= 2.1.2 < 3" - checksum: bd9f120f5a5b306f0bc0b9ae1edeb1577161503f5f8252a20f1a9e56ef8775c9959fd01c55f2d3a39d9a8abaf3e30c1abeb1895f367dcbbe0a8fd1c9ca01c4f6 + fs.realpath: ^1.0.0 + minimatch: ^8.0.2 + minipass: ^4.2.4 + path-scurry: ^1.6.1 + checksum: 94b093adbc591bc36b582f77927d1fb0dbf3ccc231828512b017601408be98d1fe798fc8c0b19c6f2d1a7660339c3502ce698de475e9d938ccbb69b47b647c84 languageName: node linkType: hard -"iconv-lite@npm:^0.6.2": - version: 0.6.3 - resolution: "iconv-lite@npm:0.6.3" +"glob@npm:^5.0.15": + version: 5.0.15 + resolution: "glob@npm:5.0.15" dependencies: - safer-buffer: ">= 2.1.2 < 3.0.0" - checksum: 3f60d47a5c8fc3313317edfd29a00a692cc87a19cac0159e2ce711d0ebc9019064108323b5e493625e25594f11c6236647d8e256fbe7a58f4a3b33b89e6d30bf + inflight: ^1.0.4 + inherits: 2 + minimatch: 2 || 3 + once: ^1.3.0 + path-is-absolute: ^1.0.0 + checksum: f9742448303460672607e569457f1b57e486a79a985e269b69465834d2075b243378225f65dc54c09fcd4b75e4fb34442aec88f33f8c65fa4abccc8ee2dc2f5d languageName: node linkType: hard -"idna-uts46-hx@npm:^2.3.1": - version: 2.3.1 - resolution: "idna-uts46-hx@npm:2.3.1" +"glob@npm:^7.1.2": + version: 7.2.3 + resolution: "glob@npm:7.2.3" dependencies: - punycode: 2.1.0 - checksum: d434c3558d2bc1090eb90f978f995101f469cb26593414ac57aa082c9352e49972b332c6e4188b9b15538172ccfeae3121e5a19b96972a97e6aeb0676d86639c + fs.realpath: ^1.0.0 + inflight: ^1.0.4 + inherits: 2 + minimatch: ^3.1.1 + once: ^1.3.0 + path-is-absolute: ^1.0.0 + checksum: 29452e97b38fa704dabb1d1045350fb2467cf0277e155aa9ff7077e90ad81d1ea9d53d3ee63bd37c05b09a065e90f16aec4a65f5b8de401d1dac40bc5605d133 languageName: node linkType: hard -"ieee754@npm:^1.1.13, ieee754@npm:^1.1.4, ieee754@npm:^1.2.1": - version: 1.2.1 - resolution: "ieee754@npm:1.2.1" - checksum: 5144c0c9815e54ada181d80a0b810221a253562422e7c6c3a60b1901154184f49326ec239d618c416c1c5945a2e197107aee8d986a3dd836b53dffefd99b5e7e +"glob@npm:^8.1.0": + version: 8.1.0 + resolution: "glob@npm:8.1.0" + dependencies: + fs.realpath: ^1.0.0 + inflight: ^1.0.4 + inherits: 2 + minimatch: ^5.0.1 + once: ^1.3.0 + checksum: 92fbea3221a7d12075f26f0227abac435de868dd0736a17170663783296d0dd8d3d532a5672b4488a439bf5d7fb85cdd07c11185d6cd39184f0385cbdfb86a47 languageName: node linkType: hard -"ignore@npm:^4.0.6": - version: 4.0.6 - resolution: "ignore@npm:4.0.6" - checksum: 248f82e50a430906f9ee7f35e1158e3ec4c3971451dd9f99c9bc1548261b4db2b99709f60ac6c6cac9333494384176cc4cc9b07acbe42d52ac6a09cad734d800 +"global-modules@npm:^2.0.0": + version: 2.0.0 + resolution: "global-modules@npm:2.0.0" + dependencies: + global-prefix: ^3.0.0 + checksum: d6197f25856c878c2fb5f038899f2dca7cbb2f7b7cf8999660c0104972d5cfa5c68b5a0a77fa8206bb536c3903a4615665acb9709b4d80846e1bb47eaef65430 languageName: node linkType: hard -"ignore@npm:^5.1.1, ignore@npm:^5.1.4, ignore@npm:^5.1.8": - version: 5.1.8 - resolution: "ignore@npm:5.1.8" - checksum: 967abadb61e2cb0e5c5e8c4e1686ab926f91bc1a4680d994b91947d3c65d04c3ae126dcdf67f08e0feeb8ff8407d453e641aeeddcc47a3a3cca359f283cf6121 +"global-prefix@npm:^3.0.0": + version: 3.0.0 + resolution: "global-prefix@npm:3.0.0" + dependencies: + ini: ^1.3.5 + kind-of: ^6.0.2 + which: ^1.3.1 + checksum: 8a82fc1d6f22c45484a4e34656cc91bf021a03e03213b0035098d605bfc612d7141f1e14a21097e8a0413b4884afd5b260df0b6a25605ce9d722e11f1df2881d languageName: node linkType: hard -"ignore@npm:^5.2.0": - version: 5.2.4 - resolution: "ignore@npm:5.2.4" - checksum: 3d4c309c6006e2621659311783eaea7ebcd41fe4ca1d78c91c473157ad6666a57a2df790fe0d07a12300d9aac2888204d7be8d59f9aaf665b1c7fcdb432517ef +"global@npm:~4.4.0": + version: 4.4.0 + resolution: "global@npm:4.4.0" + dependencies: + min-document: ^2.19.0 + process: ^0.11.10 + checksum: 9c057557c8f5a5bcfbeb9378ba4fe2255d04679452be504608dd5f13b54edf79f7be1db1031ea06a4ec6edd3b9f5f17d2d172fb47e6c69dae57fd84b7e72b77f languageName: node linkType: hard -"immediate@npm:^3.2.3": - version: 3.3.0 - resolution: "immediate@npm:3.3.0" - checksum: 634b4305101e2452eba6c07d485bf3e415995e533c94b9c3ffbc37026fa1be34def6e4f2276b0dc2162a3f91628564a4bfb26280278b89d3ee54624e854d2f5f +"globals@npm:^11.7.0": + version: 11.12.0 + resolution: "globals@npm:11.12.0" + checksum: 67051a45eca3db904aee189dfc7cd53c20c7d881679c93f6146ddd4c9f4ab2268e68a919df740d39c71f4445d2b38ee360fc234428baea1dbdfe68bbcb46979e languageName: node linkType: hard -"immediate@npm:~3.2.3": - version: 3.2.3 - resolution: "immediate@npm:3.2.3" - checksum: 9867dc70794f3aa246a90afe8a0166607590b687e8c572839ff2342292ac2da4b1cdfd396d38f7b9e72625d817d601e73c33c2874e9c0b8e0f1d6658b3c03496 +"globals@npm:^13.19.0": + version: 13.24.0 + resolution: "globals@npm:13.24.0" + dependencies: + type-fest: ^0.20.2 + checksum: 56066ef058f6867c04ff203b8a44c15b038346a62efbc3060052a1016be9f56f4cf0b2cd45b74b22b81e521a889fc7786c73691b0549c2f3a6e825b3d394f43c languageName: node linkType: hard -"immutable@npm:4.2.1": - version: 4.2.1 - resolution: "immutable@npm:4.2.1" - checksum: 525bd78c4b8550df1b5f12d3bc7eb8bb3daed24f97df4018ec99a16436fc2a03fcebfcb4d3d36c86c46039292a583ea9eceb8a55704932f70a0cc5f15695b42a +"globalthis@npm:^1.0.3": + version: 1.0.3 + resolution: "globalthis@npm:1.0.3" + dependencies: + define-properties: ^1.1.3 + checksum: fbd7d760dc464c886d0196166d92e5ffb4c84d0730846d6621a39fbbc068aeeb9c8d1421ad330e94b7bca4bb4ea092f5f21f3d36077812af5d098b4dc006c998 languageName: node linkType: hard -"immutable@npm:^4.0.0-rc.12": - version: 4.1.0 - resolution: "immutable@npm:4.1.0" - checksum: b9bc1f14fb18eb382d48339c064b24a1f97ae4cf43102e0906c0a6e186a27afcd18b55ca4a0b63c98eefb58143e2b5ebc7755a5fb4da4a7ad84b7a6096ac5b13 +"globby@npm:^10.0.1": + version: 10.0.2 + resolution: "globby@npm:10.0.2" + dependencies: + "@types/glob": ^7.1.1 + array-union: ^2.1.0 + dir-glob: ^3.0.1 + fast-glob: ^3.0.3 + glob: ^7.1.3 + ignore: ^5.1.1 + merge2: ^1.2.3 + slash: ^3.0.0 + checksum: 167cd067f2cdc030db2ec43232a1e835fa06217577d545709dbf29fd21631b30ff8258705172069c855dc4d5766c3b2690834e35b936fbff01ad0329fb95a26f languageName: node linkType: hard -"import-fresh@npm:^2.0.0": - version: 2.0.0 - resolution: "import-fresh@npm:2.0.0" +"globby@npm:^11.1.0": + version: 11.1.0 + resolution: "globby@npm:11.1.0" dependencies: - caller-path: ^2.0.0 - resolve-from: ^3.0.0 - checksum: 610255f9753cc6775df00be08e9f43691aa39f7703e3636c45afe22346b8b545e600ccfe100c554607546fc8e861fa149a0d1da078c8adedeea30fff326eef79 + array-union: ^2.1.0 + dir-glob: ^3.0.1 + fast-glob: ^3.2.9 + ignore: ^5.2.0 + merge2: ^1.4.1 + slash: ^3.0.0 + checksum: b4be8885e0cfa018fc783792942d53926c35c50b3aefd3fdcfb9d22c627639dc26bd2327a40a0b74b074100ce95bb7187bfeae2f236856aa3de183af7a02aea6 languageName: node linkType: hard -"import-fresh@npm:^3.0.0, import-fresh@npm:^3.2.1": - version: 3.3.0 - resolution: "import-fresh@npm:3.3.0" +"gluegun@npm:5.1.2": + version: 5.1.2 + resolution: "gluegun@npm:5.1.2" dependencies: - parent-module: ^1.0.0 - resolve-from: ^4.0.0 - checksum: 2cacfad06e652b1edc50be650f7ec3be08c5e5a6f6d12d035c440a42a8cc028e60a5b99ca08a77ab4d6b1346da7d971915828f33cdab730d3d42f08242d09baa + apisauce: ^2.1.5 + app-module-path: ^2.2.0 + cli-table3: 0.6.0 + colors: 1.4.0 + cosmiconfig: 7.0.1 + cross-spawn: 7.0.3 + ejs: 3.1.6 + enquirer: 2.3.6 + execa: 5.1.1 + fs-jetpack: 4.3.1 + lodash.camelcase: ^4.3.0 + lodash.kebabcase: ^4.1.1 + lodash.lowercase: ^4.3.0 + lodash.lowerfirst: ^4.3.1 + lodash.pad: ^4.5.1 + lodash.padend: ^4.6.1 + lodash.padstart: ^4.6.1 + lodash.repeat: ^4.1.0 + lodash.snakecase: ^4.1.1 + lodash.startcase: ^4.4.0 + lodash.trim: ^4.5.1 + lodash.trimend: ^4.5.1 + lodash.trimstart: ^4.5.1 + lodash.uppercase: ^4.3.0 + lodash.upperfirst: ^4.3.1 + ora: 4.0.2 + pluralize: ^8.0.0 + semver: 7.3.5 + which: 2.0.2 + yargs-parser: ^21.0.0 + bin: + gluegun: bin/gluegun + checksum: 2c91934b98022018a524a3be32efb3e4567905a618ccb4aca4f19207ff4b37262bc18264b306f1c82757eaab634bac6c06aacff16059b11a38deefd07b6293b6 languageName: node linkType: hard -"imul@npm:^1.0.0": +"gopd@npm:^1.0.1": version: 1.0.1 - resolution: "imul@npm:1.0.1" - checksum: 6c2af3d5f09e2135e14d565a2c108412b825b221eb2c881f9130467f2adccf7ae201773ae8bcf1be169e2d090567a1fdfa9cf20d3b7da7b9cecb95b920ff3e52 + resolution: "gopd@npm:1.0.1" + dependencies: + get-intrinsic: ^1.1.3 + checksum: a5ccfb8806e0917a94e0b3de2af2ea4979c1da920bc381667c260e00e7cafdbe844e2cb9c5bcfef4e5412e8bf73bab837285bc35c7ba73aaaf0134d4583393a6 languageName: node linkType: hard -"imurmurhash@npm:^0.1.4": - version: 0.1.4 - resolution: "imurmurhash@npm:0.1.4" - checksum: 7cae75c8cd9a50f57dadd77482359f659eaebac0319dd9368bcd1714f55e65badd6929ca58569da2b6494ef13fdd5598cd700b1eba23f8b79c5f19d195a3ecf7 +"got@npm:12.1.0": + version: 12.1.0 + resolution: "got@npm:12.1.0" + dependencies: + "@sindresorhus/is": ^4.6.0 + "@szmarczak/http-timer": ^5.0.1 + "@types/cacheable-request": ^6.0.2 + "@types/responselike": ^1.0.0 + cacheable-lookup: ^6.0.4 + cacheable-request: ^7.0.2 + decompress-response: ^6.0.0 + form-data-encoder: 1.7.1 + get-stream: ^6.0.1 + http2-wrapper: ^2.1.10 + lowercase-keys: ^3.0.0 + p-cancelable: ^3.0.0 + responselike: ^2.0.0 + checksum: 1cc9af6ca511338a7f1bbb0943999e6ac324ea3c7d826066c02e530b4ac41147b1a4cadad21b28c3938de82185ac99c33d64a3a4560c6e0b0b125191ba6ee619 languageName: node linkType: hard -"in-publish@npm:^2.0.0": - version: 2.0.1 - resolution: "in-publish@npm:2.0.1" - bin: - in-install: in-install.js - in-publish: in-publish.js - not-in-install: not-in-install.js - not-in-publish: not-in-publish.js - checksum: 5efde2992a1e76550614a5a2c51f53669d9f3ee3a11d364de22b0c77c41de0b87c52c4c9b04375eaa276761b1944dd2b166323894d2344192328ffe85927ad38 +"got@npm:^11.8.5": + version: 11.8.5 + resolution: "got@npm:11.8.5" + dependencies: + "@sindresorhus/is": ^4.0.0 + "@szmarczak/http-timer": ^4.0.5 + "@types/cacheable-request": ^6.0.1 + "@types/responselike": ^1.0.0 + cacheable-lookup: ^5.0.3 + cacheable-request: ^7.0.2 + decompress-response: ^6.0.0 + http2-wrapper: ^1.0.0-beta.5.2 + lowercase-keys: ^2.0.0 + p-cancelable: ^2.0.0 + responselike: ^2.0.0 + checksum: 2de8a1bbda4e9b6b2b72b2d2100bc055a59adc1740529e631f61feb44a8b9a1f9f8590941ed9da9df0090b6d6d0ed8ffee94cd9ac086ec3409b392b33440f7d2 languageName: node linkType: hard -"indent-string@npm:^4.0.0": - version: 4.0.0 - resolution: "indent-string@npm:4.0.0" - checksum: 824cfb9929d031dabf059bebfe08cf3137365e112019086ed3dcff6a0a7b698cb80cf67ccccde0e25b9e2d7527aa6cc1fed1ac490c752162496caba3e6699612 +"graceful-fs@npm:^4.1.2, graceful-fs@npm:^4.2.4": + version: 4.2.10 + resolution: "graceful-fs@npm:4.2.10" + checksum: 3f109d70ae123951905d85032ebeae3c2a5a7a997430df00ea30df0e3a6c60cf6689b109654d6fdacd28810a053348c4d14642da1d075049e6be1ba5216218da languageName: node linkType: hard -"infer-owner@npm:^1.0.4": - version: 1.0.4 - resolution: "infer-owner@npm:1.0.4" - checksum: 181e732764e4a0611576466b4b87dac338972b839920b2a8cde43642e4ed6bd54dc1fb0b40874728f2a2df9a1b097b8ff83b56d5f8f8e3927f837fdcb47d8a89 +"graceful-fs@npm:^4.1.6, graceful-fs@npm:^4.2.0, graceful-fs@npm:^4.2.6": + version: 4.2.8 + resolution: "graceful-fs@npm:4.2.8" + checksum: 5d224c8969ad0581d551dfabdb06882706b31af2561bd5e2034b4097e67cc27d05232849b8643866585fd0a41c7af152950f8776f4dd5579e9853733f31461c6 languageName: node linkType: hard -"inflight@npm:^1.0.4": - version: 1.0.6 - resolution: "inflight@npm:1.0.6" - dependencies: - once: ^1.3.0 - wrappy: 1 - checksum: f4f76aa072ce19fae87ce1ef7d221e709afb59d445e05d47fba710e85470923a75de35bfae47da6de1b18afc3ce83d70facf44cfb0aff89f0a3f45c0a0244dfd +"graphemer@npm:^1.4.0": + version: 1.4.0 + resolution: "graphemer@npm:1.4.0" + checksum: bab8f0be9b568857c7bec9fda95a89f87b783546d02951c40c33f84d05bb7da3fd10f863a9beb901463669b6583173a8c8cc6d6b306ea2b9b9d5d3d943c3a673 languageName: node linkType: hard -"inherits@npm:2, inherits@npm:2.0.4, inherits@npm:^2.0.1, inherits@npm:^2.0.3, inherits@npm:^2.0.4, inherits@npm:~2.0.1, inherits@npm:~2.0.3, inherits@npm:~2.0.4": - version: 2.0.4 - resolution: "inherits@npm:2.0.4" - checksum: 4a48a733847879d6cf6691860a6b1e3f0f4754176e4d71494c41f3475553768b10f84b5ce1d40fbd0e34e6bfbb864ee35858ad4dd2cf31e02fc4a154b724d7f1 +"graphql-import-node@npm:^0.0.5": + version: 0.0.5 + resolution: "graphql-import-node@npm:0.0.5" + peerDependencies: + graphql: "*" + checksum: a9af565f3422e9e732dcf97077deff3f94b9af0d7e8001bb65a3cac607a462664f902b3603ead1626b294928c4b6302cb6aa2d49254444d465ce87c629fb842d languageName: node linkType: hard -"ini@npm:^1.3.5, ini@npm:~1.3.0": - version: 1.3.8 - resolution: "ini@npm:1.3.8" - checksum: dfd98b0ca3a4fc1e323e38a6c8eb8936e31a97a918d3b377649ea15bdb15d481207a0dda1021efbd86b464cae29a0d33c1d7dcaf6c5672bee17fa849bc50a1b3 +"graphql@npm:15.5.0": + version: 15.5.0 + resolution: "graphql@npm:15.5.0" + checksum: 58a69f7274ae94c690bfa2517f96bbaf1327e1ca1fc46606e772ba2f7ca517adeb375346301373351e693022f448b7866163034209623d7c5315819ef8c5e7c0 languageName: node linkType: hard -"inquirer@npm:0.11.0": - version: 0.11.0 - resolution: "inquirer@npm:0.11.0" - dependencies: - ansi-escapes: ^1.1.0 - ansi-regex: ^2.0.0 - chalk: ^1.0.0 - cli-cursor: ^1.0.1 - cli-width: ^1.0.1 - figures: ^1.3.5 - lodash: ^3.3.1 - readline2: ^1.0.1 - run-async: ^0.1.0 - rx-lite: ^3.1.2 - strip-ansi: ^3.0.0 - through: ^2.3.6 - checksum: f36903494ccc04b1f21c1be3121c1c187582a10fd6b756e6aa3d69b33079413e37d717cd36795770a17fd4c0cec58ec8232d6af3e1452e504f97fb93b5768b51 +"graphql@npm:^16.6.0": + version: 16.7.1 + resolution: "graphql@npm:16.7.1" + checksum: c924d8428daf0e96a5ea43e9bc3cd1b6802899907d284478ac8f705c8fd233a0a51eef915f7569fb5de8acb2e85b802ccc6c85c2b157ad805c1e9adba5a299bd languageName: node linkType: hard -"inquirer@npm:^6.2.2": - version: 6.5.2 - resolution: "inquirer@npm:6.5.2" - dependencies: - ansi-escapes: ^3.2.0 - chalk: ^2.4.2 - cli-cursor: ^2.1.0 - cli-width: ^2.0.0 - external-editor: ^3.0.3 - figures: ^2.0.0 - lodash: ^4.17.12 - mute-stream: 0.0.7 - run-async: ^2.2.0 - rxjs: ^6.4.0 - string-width: ^2.1.0 - strip-ansi: ^5.1.0 - through: ^2.3.6 - checksum: 175ad4cd1ebed493b231b240185f1da5afeace5f4e8811dfa83cf55dcae59c3255eaed990aa71871b0fd31aa9dc212f43c44c50ed04fb529364405e72f484d28 +"growl@npm:1.10.5": + version: 1.10.5 + resolution: "growl@npm:1.10.5" + checksum: 4b86685de6831cebcbb19f93870bea624afee61124b0a20c49017013987cd129e73a8c4baeca295728f41d21265e1f859d25ef36731b142ca59c655fea94bb1a languageName: node linkType: hard -"interface-datastore@npm:^6.0.2": - version: 6.1.1 - resolution: "interface-datastore@npm:6.1.1" +"handlebars@npm:^4.0.1, handlebars@npm:^4.0.5": + version: 4.7.7 + resolution: "handlebars@npm:4.7.7" dependencies: - interface-store: ^2.0.2 - nanoid: ^3.0.2 - uint8arrays: ^3.0.0 - checksum: a0388adabf029be229bbfce326bbe64fd3353373512e7e6ed4283e06710bfa141db118e3536f8535a65016a0abeec631b888d42790b00637879d6ae56cf728cd + minimist: ^1.2.5 + neo-async: ^2.6.0 + source-map: ^0.6.1 + uglify-js: ^3.1.4 + wordwrap: ^1.0.0 + dependenciesMeta: + uglify-js: + optional: true + bin: + handlebars: bin/handlebars + checksum: 1e79a43f5e18d15742977cb987923eab3e2a8f44f2d9d340982bcb69e1735ed049226e534d7c1074eaddaf37e4fb4f471a8adb71cddd5bc8cf3f894241df5cee languageName: node linkType: hard -"interface-store@npm:^2.0.2": - version: 2.0.2 - resolution: "interface-store@npm:2.0.2" - checksum: 0e80adb1de9ff57687cfa1b08499702b72cacf33a7e0320ac7781989f3685d73f2a84996358f540250229afa19c7acebf03085087762f718035622ea6a1a5b8a +"har-schema@npm:^2.0.0": + version: 2.0.0 + resolution: "har-schema@npm:2.0.0" + checksum: d8946348f333fb09e2bf24cc4c67eabb47c8e1d1aa1c14184c7ffec1140a49ec8aa78aa93677ae452d71d5fc0fdeec20f0c8c1237291fc2bcb3f502a5d204f9b languageName: node linkType: hard -"internal-slot@npm:^1.0.3": - version: 1.0.3 - resolution: "internal-slot@npm:1.0.3" +"har-validator@npm:~5.1.3": + version: 5.1.5 + resolution: "har-validator@npm:5.1.5" dependencies: - get-intrinsic: ^1.1.0 - has: ^1.0.3 - side-channel: ^1.0.4 - checksum: 1944f92e981e47aebc98a88ff0db579fd90543d937806104d0b96557b10c1f170c51fb777b97740a8b6ddeec585fca8c39ae99fd08a8e058dfc8ab70937238bf + ajv: ^6.12.3 + har-schema: ^2.0.0 + checksum: b998a7269ca560d7f219eedc53e2c664cd87d487e428ae854a6af4573fc94f182fe9d2e3b92ab968249baec7ebaf9ead69cf975c931dc2ab282ec182ee988280 languageName: node linkType: hard -"internal-slot@npm:^1.0.5": - version: 1.0.5 - resolution: "internal-slot@npm:1.0.5" +"hardhat-contract-sizer@npm:^2.1.1": + version: 2.6.1 + resolution: "hardhat-contract-sizer@npm:2.6.1" dependencies: - get-intrinsic: ^1.2.0 - has: ^1.0.3 - side-channel: ^1.0.4 - checksum: 97e84046bf9e7574d0956bd98d7162313ce7057883b6db6c5c7b5e5f05688864b0978ba07610c726d15d66544ffe4b1050107d93f8a39ebc59b15d8b429b497a + chalk: ^4.0.0 + cli-table3: ^0.6.0 + peerDependencies: + hardhat: ^2.0.0 + checksum: a82ae2405a8571e8b0cd0a21dea9a10946b342f1ada04c72c9cbe28fca955f9a2b1394c70400003f388182298dc1de00e80bf56dbfa5e36833d3c93ab1f50c0c languageName: node linkType: hard -"interpret@npm:^1.0.0": - version: 1.4.0 - resolution: "interpret@npm:1.4.0" - checksum: 2e5f51268b5941e4a17e4ef0575bc91ed0ab5f8515e3cf77486f7c14d13f3010df9c0959f37063dcc96e78d12dc6b0bb1b9e111cdfe69771f4656d2993d36155 +"hardhat-deploy@npm:^0.11.34": + version: 0.11.34 + resolution: "hardhat-deploy@npm:0.11.34" + dependencies: + "@ethersproject/abi": ^5.7.0 + "@ethersproject/abstract-signer": ^5.7.0 + "@ethersproject/address": ^5.7.0 + "@ethersproject/bignumber": ^5.7.0 + "@ethersproject/bytes": ^5.7.0 + "@ethersproject/constants": ^5.7.0 + "@ethersproject/contracts": ^5.7.0 + "@ethersproject/providers": ^5.7.2 + "@ethersproject/solidity": ^5.7.0 + "@ethersproject/transactions": ^5.7.0 + "@ethersproject/wallet": ^5.7.0 + "@types/qs": ^6.9.7 + axios: ^0.21.1 + chalk: ^4.1.2 + chokidar: ^3.5.2 + debug: ^4.3.2 + enquirer: ^2.3.6 + ethers: ^5.5.3 + form-data: ^4.0.0 + fs-extra: ^10.0.0 + match-all: ^1.2.6 + murmur-128: ^0.2.1 + qs: ^6.9.4 + zksync-web3: ^0.14.3 + checksum: 3c4bcd657a80e4f22c1f8bcee021e5277060849ce4180cbc721e0c2d625f2f98de8ebbfad23875d32eeaf06d88bdba06cb43ab29359cb9531e8bb7851a98ead1 languageName: node linkType: hard -"invariant@npm:2, invariant@npm:^2.2.2": - version: 2.2.4 - resolution: "invariant@npm:2.2.4" +"hardhat-gas-reporter@npm:^1.0.4": + version: 1.0.9 + resolution: "hardhat-gas-reporter@npm:1.0.9" dependencies: - loose-envify: ^1.0.0 - checksum: cc3182d793aad82a8d1f0af697b462939cb46066ec48bbf1707c150ad5fad6406137e91a262022c269702e01621f35ef60269f6c0d7fd178487959809acdfb14 + array-uniq: 1.0.3 + eth-gas-reporter: ^0.2.25 + sha1: ^1.1.1 + peerDependencies: + hardhat: ^2.0.2 + checksum: 77f8f8d085ff3d9d7787f0227e5355e1800f7d6707bc70171e0567bf69706703ae7f6f53dce1be1d409e7e71e3629a434c94b546bdbbc1e4c1af47cd5d0c6776 languageName: node linkType: hard -"invert-kv@npm:^1.0.0": +"hardhat-shorthand@npm:^1.0.0": version: 1.0.0 - resolution: "invert-kv@npm:1.0.0" - checksum: aebeee31dda3b3d25ffd242e9a050926e7fe5df642d60953ab183aca1a7d1ffb39922eb2618affb0e850cf2923116f0da1345367759d88d097df5da1f1e1590e + resolution: "hardhat-shorthand@npm:1.0.0" + dependencies: + "@fvictorio/tabtab": ^0.0.3 + debug: ^4.1.1 + semver: ^6.3.0 + bin: + hardhat-completion: dist/src/completion.js + hh: dist/src/index.js + checksum: df9caf38881ed72f954e4ed5703826923d74c8fe02974bf62e7547478200177f8cbf7e4aa96f55e9be638f07719dcf8f73e2e88a8643fbff6de3e8f7b56c58f9 languageName: node linkType: hard -"invert-kv@npm:^2.0.0": - version: 2.0.0 - resolution: "invert-kv@npm:2.0.0" - checksum: 52ea317354101ad6127c6e4c1c6a2d27ae8d3010b6438b60d76d6a920e55410e03547f97f9d1f52031becf5656bbef91d36ee7daa9e26ebc374a9cb342e1f127 +"hardhat@npm:^2.22.0": + version: 2.28.6 + resolution: "hardhat@npm:2.28.6" + dependencies: + "@ethereumjs/util": ^9.1.0 + "@ethersproject/abi": ^5.1.2 + "@nomicfoundation/edr": 0.12.0-next.23 + "@nomicfoundation/solidity-analyzer": ^0.1.0 + "@sentry/node": ^5.18.1 + adm-zip: ^0.4.16 + aggregate-error: ^3.0.0 + ansi-escapes: ^4.3.0 + boxen: ^5.1.2 + chokidar: ^4.0.0 + ci-info: ^2.0.0 + debug: ^4.1.1 + enquirer: ^2.3.0 + env-paths: ^2.2.0 + ethereum-cryptography: ^1.0.3 + find-up: ^5.0.0 + fp-ts: 1.19.3 + fs-extra: ^7.0.1 + immutable: ^4.0.0-rc.12 + io-ts: 1.10.4 + json-stream-stringify: ^3.1.4 + keccak: ^3.0.2 + lodash: ^4.17.11 + micro-eth-signer: ^0.14.0 + mnemonist: ^0.38.0 + mocha: ^10.0.0 + p-map: ^4.0.0 + picocolors: ^1.1.0 + raw-body: ^2.4.1 + resolve: 1.17.0 + semver: ^6.3.0 + solc: 0.8.26 + source-map-support: ^0.5.13 + stacktrace-parser: ^0.1.10 + tinyglobby: ^0.2.6 + tsort: 0.0.1 + undici: ^5.14.0 + uuid: ^8.3.2 + ws: ^7.4.6 + peerDependencies: + ts-node: "*" + typescript: "*" + peerDependenciesMeta: + ts-node: + optional: true + typescript: + optional: true + bin: + hardhat: internal/cli/bootstrap.js + checksum: ebe705fd542535f6651b92d117054edd0ab6bbe5c0aab4603dbddb6db9472fac3c521566f469a9ca3e312f766f4fcd8c0f419b1104eb005e830fb056536cad44 languageName: node linkType: hard -"io-ts@npm:1.10.4": - version: 1.10.4 - resolution: "io-ts@npm:1.10.4" +"has-ansi@npm:^2.0.0": + version: 2.0.0 + resolution: "has-ansi@npm:2.0.0" dependencies: - fp-ts: ^1.0.0 - checksum: 619134006778f7ca42693716ade7fc1a383079e7848bbeabc67a0e4ac9139cda6b2a88a052d539ab7d554033ee2ffe4dab5cb96b958c83fee2dff73d23f03e88 + ansi-regex: ^2.0.0 + checksum: 1b51daa0214440db171ff359d0a2d17bc20061164c57e76234f614c91dbd2a79ddd68dfc8ee73629366f7be45a6df5f2ea9de83f52e1ca24433f2cc78c35d8ec languageName: node linkType: hard -"ip-regex@npm:^4.0.0": - version: 4.3.0 - resolution: "ip-regex@npm:4.3.0" - checksum: 7ff904b891221b1847f3fdf3dbb3e6a8660dc39bc283f79eb7ed88f5338e1a3d1104b779bc83759159be266249c59c2160e779ee39446d79d4ed0890dfd06f08 +"has-bigints@npm:^1.0.1": + version: 1.0.1 + resolution: "has-bigints@npm:1.0.1" + checksum: 44ab55868174470065d2e0f8f6def1c990d12b82162a8803c679699fa8a39f966e336f2a33c185092fe8aea7e8bf2e85f1c26add5f29d98f2318bd270096b183 + languageName: node + linkType: hard + +"has-bigints@npm:^1.0.2": + version: 1.0.2 + resolution: "has-bigints@npm:1.0.2" + checksum: 390e31e7be7e5c6fe68b81babb73dfc35d413604d7ee5f56da101417027a4b4ce6a27e46eff97ad040c835b5d228676eae99a9b5c3bc0e23c8e81a49241ff45b languageName: node linkType: hard -"ip@npm:^1.1.5": - version: 1.1.5 - resolution: "ip@npm:1.1.5" - checksum: 30133981f082a060a32644f6a7746e9ba7ac9e2bc07ecc8bbdda3ee8ca9bec1190724c390e45a1ee7695e7edfd2a8f7dda2c104ec5f7ac5068c00648504c7e5a +"has-flag@npm:^1.0.0": + version: 1.0.0 + resolution: "has-flag@npm:1.0.0" + checksum: ce3f8ae978e70f16e4bbe17d3f0f6d6c0a3dd3b62a23f97c91d0fda9ed8e305e13baf95cc5bee4463b9f25ac9f5255de113165c5fb285e01b8065b2ac079b301 languageName: node linkType: hard -"ipaddr.js@npm:1.9.1": - version: 1.9.1 - resolution: "ipaddr.js@npm:1.9.1" - checksum: f88d3825981486f5a1942414c8d77dd6674dd71c065adcfa46f578d677edcb99fda25af42675cb59db492fdf427b34a5abfcde3982da11a8fd83a500b41cfe77 +"has-flag@npm:^3.0.0": + version: 3.0.0 + resolution: "has-flag@npm:3.0.0" + checksum: 4a15638b454bf086c8148979aae044dd6e39d63904cd452d970374fa6a87623423da485dfb814e7be882e05c096a7ccf1ebd48e7e7501d0208d8384ff4dea73b languageName: node linkType: hard -"ipfs-core-types@npm:^0.9.0": - version: 0.9.0 - resolution: "ipfs-core-types@npm:0.9.0" - dependencies: - interface-datastore: ^6.0.2 - multiaddr: ^10.0.0 - multiformats: ^9.4.13 - checksum: 22db8e039348dc372c99b45a87ce8dce81e15fa710cee410c1731004d528e0bd0da96b5a4c5571d501313fae93316af3b902c2220c486d2fade2e53f07a7d17b +"has-flag@npm:^4.0.0": + version: 4.0.0 + resolution: "has-flag@npm:4.0.0" + checksum: 261a1357037ead75e338156b1f9452c016a37dcd3283a972a30d9e4a87441ba372c8b81f818cd0fbcd9c0354b4ae7e18b9e1afa1971164aef6d18c2b6095a8ad languageName: node linkType: hard -"ipfs-core-utils@npm:^0.13.0": - version: 0.13.0 - resolution: "ipfs-core-utils@npm:0.13.0" +"has-property-descriptors@npm:^1.0.0": + version: 1.0.0 + resolution: "has-property-descriptors@npm:1.0.0" dependencies: - any-signal: ^2.1.2 - blob-to-it: ^1.0.1 - browser-readablestream-to-it: ^1.0.1 - debug: ^4.1.1 - err-code: ^3.0.1 - ipfs-core-types: ^0.9.0 - ipfs-unixfs: ^6.0.3 - ipfs-utils: ^9.0.2 - it-all: ^1.0.4 - it-map: ^1.0.4 - it-peekable: ^1.0.2 - it-to-stream: ^1.0.0 - merge-options: ^3.0.4 - multiaddr: ^10.0.0 - multiaddr-to-uri: ^8.0.0 - multiformats: ^9.4.13 - nanoid: ^3.1.23 - parse-duration: ^1.0.0 - timeout-abort-controller: ^2.0.0 - uint8arrays: ^3.0.0 - checksum: af46717a69cf2e4f1bfbd77c7c1951eaa8b9619bdb888ca971849dc2d2468aceb0238e2f47ae45568478b2ceb1428ae7061239afc92aac06691f7bea9e21e4eb + get-intrinsic: ^1.1.1 + checksum: a6d3f0a266d0294d972e354782e872e2fe1b6495b321e6ef678c9b7a06a40408a6891817350c62e752adced73a94ac903c54734fee05bf65b1905ee1368194bb languageName: node linkType: hard -"ipfs-http-client@npm:55.0.0": - version: 55.0.0 - resolution: "ipfs-http-client@npm:55.0.0" - dependencies: - "@ipld/dag-cbor": ^7.0.0 - "@ipld/dag-json": ^8.0.1 - "@ipld/dag-pb": ^2.1.3 - abort-controller: ^3.0.0 - any-signal: ^2.1.2 - debug: ^4.1.1 - err-code: ^3.0.1 - ipfs-core-types: ^0.9.0 - ipfs-core-utils: ^0.13.0 - ipfs-utils: ^9.0.2 - it-first: ^1.0.6 - it-last: ^1.0.4 - merge-options: ^3.0.4 - multiaddr: ^10.0.0 - multiformats: ^9.4.13 - native-abort-controller: ^1.0.3 - parse-duration: ^1.0.0 - stream-to-it: ^0.2.2 - uint8arrays: ^3.0.0 - checksum: b44394475dd9f6ef2e68cf22fb5bacf93c1a8967712f12a56baf9e90f183d625569bcabfe2e7c0d1cd2f0a2eed577ab8282f5a737552faf83d3b8a82d7910494 +"has-proto@npm:^1.0.1": + version: 1.0.1 + resolution: "has-proto@npm:1.0.1" + checksum: febc5b5b531de8022806ad7407935e2135f1cc9e64636c3916c6842bd7995994ca3b29871ecd7954bd35f9e2986c17b3b227880484d22259e2f8e6ce63fd383e languageName: node linkType: hard -"ipfs-unixfs@npm:^6.0.3": - version: 6.0.9 - resolution: "ipfs-unixfs@npm:6.0.9" - dependencies: - err-code: ^3.0.1 - protobufjs: ^6.10.2 - checksum: 025d852c3cfb09b813b35f7a4f7a06bd0ff904f88b35cdf54c6ea1eb021f1597ab9c2739adabbae9cfe645a2323598bd7974ff4a8898701bc4ba92842bf21736 +"has-symbols@npm:^1.0.0, has-symbols@npm:^1.0.3": + version: 1.0.3 + resolution: "has-symbols@npm:1.0.3" + checksum: a054c40c631c0d5741a8285010a0777ea0c068f99ed43e5d6eb12972da223f8af553a455132fdb0801bdcfa0e0f443c0c03a68d8555aa529b3144b446c3f2410 languageName: node linkType: hard -"ipfs-utils@npm:^9.0.2": - version: 9.0.14 - resolution: "ipfs-utils@npm:9.0.14" - dependencies: - any-signal: ^3.0.0 - browser-readablestream-to-it: ^1.0.0 - buffer: ^6.0.1 - electron-fetch: ^1.7.2 - err-code: ^3.0.1 - is-electron: ^2.2.0 - iso-url: ^1.1.5 - it-all: ^1.0.4 - it-glob: ^1.0.1 - it-to-stream: ^1.0.0 - merge-options: ^3.0.4 - nanoid: ^3.1.20 - native-fetch: ^3.0.0 - node-fetch: ^2.6.8 - react-native-fetch-api: ^3.0.0 - stream-to-it: ^0.2.2 - checksum: 08108e03ea7b90e0fa11b76a4e24bd29d7e027c603494b53c1cc37b367fb559eaeea7b0f10b2e83ee419d50cdcb4d8105febdf185cab75c7e55afd4c8ed51aba +"has-symbols@npm:^1.0.1, has-symbols@npm:^1.0.2": + version: 1.0.2 + resolution: "has-symbols@npm:1.0.2" + checksum: 2309c426071731be792b5be43b3da6fb4ed7cbe8a9a6bcfca1862587709f01b33d575ce8f5c264c1eaad09fca2f9a8208c0a2be156232629daa2dd0c0740976b languageName: node linkType: hard -"is-accessor-descriptor@npm:^0.1.6": - version: 0.1.6 - resolution: "is-accessor-descriptor@npm:0.1.6" +"has-tostringtag@npm:^1.0.0": + version: 1.0.0 + resolution: "has-tostringtag@npm:1.0.0" dependencies: - kind-of: ^3.0.2 - checksum: 3d629a086a9585bc16a83a8e8a3416f400023301855cafb7ccc9a1d63145b7480f0ad28877dcc2cce09492c4ec1c39ef4c071996f24ee6ac626be4217b8ffc8a + has-symbols: ^1.0.2 + checksum: cc12eb28cb6ae22369ebaad3a8ab0799ed61270991be88f208d508076a1e99abe4198c965935ce85ea90b60c94ddda73693b0920b58e7ead048b4a391b502c1c languageName: node linkType: hard -"is-accessor-descriptor@npm:^1.0.0": - version: 1.0.0 - resolution: "is-accessor-descriptor@npm:1.0.0" - dependencies: - kind-of: ^6.0.0 - checksum: 8e475968e9b22f9849343c25854fa24492dbe8ba0dea1a818978f9f1b887339190b022c9300d08c47fe36f1b913d70ce8cbaca00369c55a56705fdb7caed37fe +"has-unicode@npm:^2.0.0": + version: 2.0.1 + resolution: "has-unicode@npm:2.0.1" + checksum: 1eab07a7436512db0be40a710b29b5dc21fa04880b7f63c9980b706683127e3c1b57cb80ea96d47991bdae2dfe479604f6a1ba410106ee1046a41d1bd0814400 languageName: node linkType: hard -"is-arguments@npm:^1.0.4": - version: 1.1.1 - resolution: "is-arguments@npm:1.1.1" +"has@npm:^1.0.3": + version: 1.0.3 + resolution: "has@npm:1.0.3" dependencies: - call-bind: ^1.0.2 - has-tostringtag: ^1.0.0 - checksum: 7f02700ec2171b691ef3e4d0e3e6c0ba408e8434368504bb593d0d7c891c0dbfda6d19d30808b904a6cb1929bca648c061ba438c39f296c2a8ca083229c49f27 + function-bind: ^1.1.1 + checksum: b9ad53d53be4af90ce5d1c38331e712522417d017d5ef1ebd0507e07c2fbad8686fffb8e12ddecd4c39ca9b9b47431afbb975b8abf7f3c3b82c98e9aad052792 languageName: node linkType: hard -"is-array-buffer@npm:^3.0.1, is-array-buffer@npm:^3.0.2": - version: 3.0.2 - resolution: "is-array-buffer@npm:3.0.2" +"hash-base@npm:^3.0.0": + version: 3.1.0 + resolution: "hash-base@npm:3.1.0" dependencies: - call-bind: ^1.0.2 - get-intrinsic: ^1.2.0 - is-typed-array: ^1.1.10 - checksum: dcac9dda66ff17df9cabdc58214172bf41082f956eab30bb0d86bc0fab1e44b690fc8e1f855cf2481245caf4e8a5a006a982a71ddccec84032ed41f9d8da8c14 + inherits: ^2.0.4 + readable-stream: ^3.6.0 + safe-buffer: ^5.2.0 + checksum: 26b7e97ac3de13cb23fc3145e7e3450b0530274a9562144fc2bf5c1e2983afd0e09ed7cc3b20974ba66039fad316db463da80eb452e7373e780cbee9a0d2f2dc languageName: node linkType: hard -"is-arrayish@npm:^0.2.1": - version: 0.2.1 - resolution: "is-arrayish@npm:0.2.1" - checksum: eef4417e3c10e60e2c810b6084942b3ead455af16c4509959a27e490e7aee87cfb3f38e01bbde92220b528a0ee1a18d52b787e1458ee86174d8c7f0e58cd488f +"hash.js@npm:1.1.3": + version: 1.1.3 + resolution: "hash.js@npm:1.1.3" + dependencies: + inherits: ^2.0.3 + minimalistic-assert: ^1.0.0 + checksum: 93de6f178bf71feee38f66868a57ecb5602d937c1ccd69951b0bfec1488813b6afdbb4a81ddb2c62488c419b4a35af352298b006f14c9cfbf5b872c4191b657f languageName: node linkType: hard -"is-bigint@npm:^1.0.1": - version: 1.0.4 - resolution: "is-bigint@npm:1.0.4" +"hash.js@npm:1.1.7, hash.js@npm:^1.0.0, hash.js@npm:^1.0.3, hash.js@npm:^1.1.7": + version: 1.1.7 + resolution: "hash.js@npm:1.1.7" dependencies: - has-bigints: ^1.0.1 - checksum: c56edfe09b1154f8668e53ebe8252b6f185ee852a50f9b41e8d921cb2bed425652049fbe438723f6cb48a63ca1aa051e948e7e401e093477c99c84eba244f666 + inherits: ^2.0.3 + minimalistic-assert: ^1.0.1 + checksum: e350096e659c62422b85fa508e4b3669017311aa4c49b74f19f8e1bc7f3a54a584fdfd45326d4964d6011f2b2d882e38bea775a96046f2a61b7779a979629d8f languageName: node linkType: hard -"is-binary-path@npm:~2.1.0": - version: 2.1.0 - resolution: "is-binary-path@npm:2.1.0" +"hbs-cli@npm:^1.4.1": + version: 1.4.1 + resolution: "hbs-cli@npm:1.4.1" dependencies: - binary-extensions: ^2.0.0 - checksum: 84192eb88cff70d320426f35ecd63c3d6d495da9d805b19bc65b518984b7c0760280e57dbf119b7e9be6b161784a5a673ab2c6abe83abb5198a432232ad5b35c + babel-runtime: ^5.8.34 + debug: ^2.2.0 + fs-promise: ^0.3.1 + get-stdin: ^8.0.0 + glob-promise: ^1.0.4 + handlebars: ^4.0.5 + lodash.merge: ^4.6.2 + minimist: ^1.2.0 + mkdirp-then: ^1.2.0 + resolve: ^1.1.6 + bin: + hbs: lib/index.js + checksum: ecdeb5802e48208bfadb6912ebfb91d1cc534416745779e5bb2f3c5ece2df9300ec668fa324edd25e88d547e89c0f1016d7dca769475d521f97eaf2f11c9844a languageName: node linkType: hard -"is-boolean-object@npm:^1.1.0": - version: 1.1.2 - resolution: "is-boolean-object@npm:1.1.2" - dependencies: - call-bind: ^1.0.2 - has-tostringtag: ^1.0.0 - checksum: c03b23dbaacadc18940defb12c1c0e3aaece7553ef58b162a0f6bba0c2a7e1551b59f365b91e00d2dbac0522392d576ef322628cb1d036a0fe51eb466db67222 +"he@npm:1.2.0, he@npm:^1.2.0": + version: 1.2.0 + resolution: "he@npm:1.2.0" + bin: + he: bin/he + checksum: 3d4d6babccccd79c5c5a3f929a68af33360d6445587d628087f39a965079d84f18ce9c3d3f917ee1e3978916fc833bb8b29377c3b403f919426f91bc6965e7a7 languageName: node linkType: hard -"is-buffer@npm:^1.1.5": - version: 1.1.6 - resolution: "is-buffer@npm:1.1.6" - checksum: 4a186d995d8bbf9153b4bd9ff9fd04ae75068fe695d29025d25e592d9488911eeece84eefbd8fa41b8ddcc0711058a71d4c466dcf6f1f6e1d83830052d8ca707 +"heap@npm:>= 0.2.0": + version: 0.2.7 + resolution: "heap@npm:0.2.7" + checksum: b0f3963a799e02173f994c452921a777f2b895b710119df999736bfed7477235c2860c423d9aea18a9f3b3d065cb1114d605c208cfcb8d0ac550f97ec5d28cb0 languageName: node linkType: hard -"is-buffer@npm:^2.0.5, is-buffer@npm:~2.0.3": - version: 2.0.5 - resolution: "is-buffer@npm:2.0.5" - checksum: 764c9ad8b523a9f5a32af29bdf772b08eb48c04d2ad0a7240916ac2688c983bf5f8504bf25b35e66240edeb9d9085461f9b5dae1f3d2861c6b06a65fe983de42 +"hmac-drbg@npm:^1.0.1": + version: 1.0.1 + resolution: "hmac-drbg@npm:1.0.1" + dependencies: + hash.js: ^1.0.3 + minimalistic-assert: ^1.0.0 + minimalistic-crypto-utils: ^1.0.1 + checksum: bd30b6a68d7f22d63f10e1888aee497d7c2c5c0bb469e66bbdac99f143904d1dfe95f8131f95b3e86c86dd239963c9d972fcbe147e7cffa00e55d18585c43fe0 languageName: node linkType: hard -"is-callable@npm:^1.1.3, is-callable@npm:^1.2.7": - version: 1.2.7 - resolution: "is-callable@npm:1.2.7" - checksum: 61fd57d03b0d984e2ed3720fb1c7a897827ea174bd44402878e059542ea8c4aeedee0ea0985998aa5cc2736b2fa6e271c08587addb5b3959ac52cf665173d1ac +"http-basic@npm:^8.1.1": + version: 8.1.3 + resolution: "http-basic@npm:8.1.3" + dependencies: + caseless: ^0.12.0 + concat-stream: ^1.6.2 + http-response-object: ^3.0.1 + parse-cache-control: ^1.0.1 + checksum: 7df5dc4d4b6eb8cc3beaa77f8e5c3074288ec3835abd83c85e5bb66d8a95a0ef97664d862caf5e225698cb795f78f9a5abd0d39404e5356ccd3e5e10c87936a5 languageName: node linkType: hard -"is-callable@npm:^1.1.4, is-callable@npm:^1.2.4": - version: 1.2.4 - resolution: "is-callable@npm:1.2.4" - checksum: 1a28d57dc435797dae04b173b65d6d1e77d4f16276e9eff973f994eadcfdc30a017e6a597f092752a083c1103cceb56c91e3dadc6692fedb9898dfaba701575f +"http-cache-semantics@npm:^4.0.0, http-cache-semantics@npm:^4.1.0": + version: 4.1.0 + resolution: "http-cache-semantics@npm:4.1.0" + checksum: 974de94a81c5474be07f269f9fd8383e92ebb5a448208223bfb39e172a9dbc26feff250192ecc23b9593b3f92098e010406b0f24bd4d588d631f80214648ed42 + languageName: node + linkType: hard + +"http-errors@npm:2.0.0": + version: 2.0.0 + resolution: "http-errors@npm:2.0.0" + dependencies: + depd: 2.0.0 + inherits: 2.0.4 + setprototypeof: 1.2.0 + statuses: 2.0.1 + toidentifier: 1.0.1 + checksum: 9b0a3782665c52ce9dc658a0d1560bcb0214ba5699e4ea15aefb2a496e2ca83db03ebc42e1cce4ac1f413e4e0d2d736a3fd755772c556a9a06853ba2a0b7d920 languageName: node linkType: hard -"is-ci@npm:^2.0.0": - version: 2.0.0 - resolution: "is-ci@npm:2.0.0" - dependencies: - ci-info: ^2.0.0 - bin: - is-ci: bin.js - checksum: 77b869057510f3efa439bbb36e9be429d53b3f51abd4776eeea79ab3b221337fe1753d1e50058a9e2c650d38246108beffb15ccfd443929d77748d8c0cc90144 +"http-https@npm:^1.0.0": + version: 1.0.0 + resolution: "http-https@npm:1.0.0" + checksum: 82fc4d2e512c64b35680944d1ae13e68220acfa05b06329832e271fd199c5c7fcff1f53fc1f91a1cd65a737ee4de14004dd3ba9a73cce33da970940c6e6ca774 languageName: node linkType: hard -"is-core-module@npm:^2.2.0, is-core-module@npm:^2.7.0": - version: 2.8.0 - resolution: "is-core-module@npm:2.8.0" +"http-proxy-agent@npm:^4.0.1": + version: 4.0.1 + resolution: "http-proxy-agent@npm:4.0.1" dependencies: - has: ^1.0.3 - checksum: f8b52714891e1a6c6577fcb8d5e057bab064a7a30954aab6beb5092e311473eb8da57afd334de4981dc32409ffca998412efc3a2edceb9e397cef6098d21dd91 + "@tootallnate/once": 1 + agent-base: 6 + debug: 4 + checksum: c6a5da5a1929416b6bbdf77b1aca13888013fe7eb9d59fc292e25d18e041bb154a8dfada58e223fc7b76b9b2d155a87e92e608235201f77d34aa258707963a82 languageName: node linkType: hard -"is-core-module@npm:^2.9.0": - version: 2.11.0 - resolution: "is-core-module@npm:2.11.0" +"http-response-object@npm:^3.0.1": + version: 3.0.2 + resolution: "http-response-object@npm:3.0.2" dependencies: - has: ^1.0.3 - checksum: f96fd490c6b48eb4f6d10ba815c6ef13f410b0ba6f7eb8577af51697de523e5f2cd9de1c441b51d27251bf0e4aebc936545e33a5d26d5d51f28d25698d4a8bab + "@types/node": ^10.0.3 + checksum: 6cbdcb4ce7b27c9158a131b772c903ed54add2ba831e29cc165e91c3969fa6f8105ddf924aac5b954b534ad15a1ae697b693331b2be5281ee24d79aae20c3264 languageName: node linkType: hard -"is-data-descriptor@npm:^0.1.4": - version: 0.1.4 - resolution: "is-data-descriptor@npm:0.1.4" +"http-signature@npm:~1.2.0": + version: 1.2.0 + resolution: "http-signature@npm:1.2.0" dependencies: - kind-of: ^3.0.2 - checksum: 5c622e078ba933a78338ae398a3d1fc5c23332b395312daf4f74bab4afb10d061cea74821add726cb4db8b946ba36217ee71a24fe71dd5bca4632edb7f6aad87 + assert-plus: ^1.0.0 + jsprim: ^1.2.2 + sshpk: ^1.7.0 + checksum: 3324598712266a9683585bb84a75dec4fd550567d5e0dd4a0fff6ff3f74348793404d3eeac4918fa0902c810eeee1a86419e4a2e92a164132dfe6b26743fb47c languageName: node linkType: hard -"is-data-descriptor@npm:^1.0.0": - version: 1.0.0 - resolution: "is-data-descriptor@npm:1.0.0" +"http2-wrapper@npm:^1.0.0-beta.5.2": + version: 1.0.3 + resolution: "http2-wrapper@npm:1.0.3" dependencies: - kind-of: ^6.0.0 - checksum: e705e6816241c013b05a65dc452244ee378d1c3e3842bd140beabe6e12c0d700ef23c91803f971aa7b091fb0573c5da8963af34a2b573337d87bc3e1f53a4e6d + quick-lru: ^5.1.1 + resolve-alpn: ^1.0.0 + checksum: 74160b862ec699e3f859739101ff592d52ce1cb207b7950295bf7962e4aa1597ef709b4292c673bece9c9b300efad0559fc86c71b1409c7a1e02b7229456003e languageName: node linkType: hard -"is-date-object@npm:^1.0.1": - version: 1.0.5 - resolution: "is-date-object@npm:1.0.5" +"http2-wrapper@npm:^2.1.10": + version: 2.1.11 + resolution: "http2-wrapper@npm:2.1.11" dependencies: - has-tostringtag: ^1.0.0 - checksum: baa9077cdf15eb7b58c79398604ca57379b2fc4cf9aa7a9b9e295278648f628c9b201400c01c5e0f7afae56507d741185730307cbe7cad3b9f90a77e5ee342fc + quick-lru: ^5.1.1 + resolve-alpn: ^1.2.0 + checksum: 5da05aa2c77226ac9cc82c616383f59c8f31b79897b02ecbe44b09714be1fca1f21bb184e672a669ca2830eefea4edac5f07e71c00cb5a8c5afec8e5a20cfaf7 languageName: node linkType: hard -"is-descriptor@npm:^0.1.0": - version: 0.1.6 - resolution: "is-descriptor@npm:0.1.6" +"https-proxy-agent@npm:^5.0.0": + version: 5.0.0 + resolution: "https-proxy-agent@npm:5.0.0" dependencies: - is-accessor-descriptor: ^0.1.6 - is-data-descriptor: ^0.1.4 - kind-of: ^5.0.0 - checksum: 0f780c1b46b465f71d970fd7754096ffdb7b69fd8797ca1f5069c163eaedcd6a20ec4a50af669075c9ebcfb5266d2e53c8b227e485eefdb0d1fee09aa1dd8ab6 + agent-base: 6 + debug: 4 + checksum: 165bfb090bd26d47693597661298006841ab733d0c7383a8cb2f17373387a94c903a3ac687090aa739de05e379ab6f868bae84ab4eac288ad85c328cd1ec9e53 languageName: node linkType: hard -"is-descriptor@npm:^1.0.0, is-descriptor@npm:^1.0.2": - version: 1.0.2 - resolution: "is-descriptor@npm:1.0.2" - dependencies: - is-accessor-descriptor: ^1.0.0 - is-data-descriptor: ^1.0.0 - kind-of: ^6.0.2 - checksum: 2ed623560bee035fb67b23e32ce885700bef8abe3fbf8c909907d86507b91a2c89a9d3a4d835a4d7334dd5db0237a0aeae9ca109c1e4ef1c0e7b577c0846ab5a +"human-signals@npm:^2.1.0": + version: 2.1.0 + resolution: "human-signals@npm:2.1.0" + checksum: b87fd89fce72391625271454e70f67fe405277415b48bcc0117ca73d31fa23a4241787afdc8d67f5a116cf37258c052f59ea82daffa72364d61351423848e3b8 languageName: node linkType: hard -"is-directory@npm:^0.3.1": - version: 0.3.1 - resolution: "is-directory@npm:0.3.1" - checksum: dce9a9d3981e38f2ded2a80848734824c50ee8680cd09aa477bef617949715cfc987197a2ca0176c58a9fb192a1a0d69b535c397140d241996a609d5906ae524 +"humanize-ms@npm:^1.2.1": + version: 1.2.1 + resolution: "humanize-ms@npm:1.2.1" + dependencies: + ms: ^2.0.0 + checksum: 9c7a74a2827f9294c009266c82031030eae811ca87b0da3dceb8d6071b9bde22c9f3daef0469c3c533cc67a97d8a167cd9fc0389350e5f415f61a79b171ded16 languageName: node linkType: hard -"is-docker@npm:^2.0.0": - version: 2.2.1 - resolution: "is-docker@npm:2.2.1" +"husky@npm:^8.0.1": + version: 8.0.1 + resolution: "husky@npm:8.0.1" bin: - is-docker: cli.js - checksum: 3fef7ddbf0be25958e8991ad941901bf5922ab2753c46980b60b05c1bf9c9c2402d35e6dc32e4380b980ef5e1970a5d9d5e5aa2e02d77727c3b6b5e918474c56 + husky: lib/bin.js + checksum: 943a73a13d0201318fd30e83d299bb81d866bd245b69e6277804c3b462638dc1921694cb94c2b8c920a4a187060f7d6058d3365152865406352e934c5fff70dc languageName: node linkType: hard -"is-electron@npm:^2.2.0": - version: 2.2.0 - resolution: "is-electron@npm:2.2.0" - checksum: 79e497bd5077018ed2e243c1524a2af21d9cac56962a1aa09284450f315626ca41b184f5599c9ab6526245d0cd8fe4abe962817fde48100f632c104ad5d03560 +"hyperlinker@npm:^1.0.0": + version: 1.0.0 + resolution: "hyperlinker@npm:1.0.0" + checksum: f6d020ac552e9d048668206c805a737262b4c395546c773cceea3bc45252c46b4fa6eeb67c5896499dad00d21cb2f20f89fdd480a4529cfa3d012da2957162f9 languageName: node linkType: hard -"is-extendable@npm:^0.1.0, is-extendable@npm:^0.1.1": - version: 0.1.1 - resolution: "is-extendable@npm:0.1.1" - checksum: 3875571d20a7563772ecc7a5f36cb03167e9be31ad259041b4a8f73f33f885441f778cee1f1fe0085eb4bc71679b9d8c923690003a36a6a5fdf8023e6e3f0672 +"iconv-lite@npm:0.4.24, iconv-lite@npm:^0.4.24": + version: 0.4.24 + resolution: "iconv-lite@npm:0.4.24" + dependencies: + safer-buffer: ">= 2.1.2 < 3" + checksum: bd9f120f5a5b306f0bc0b9ae1edeb1577161503f5f8252a20f1a9e56ef8775c9959fd01c55f2d3a39d9a8abaf3e30c1abeb1895f367dcbbe0a8fd1c9ca01c4f6 languageName: node linkType: hard -"is-extendable@npm:^1.0.1": - version: 1.0.1 - resolution: "is-extendable@npm:1.0.1" +"iconv-lite@npm:^0.6.2": + version: 0.6.3 + resolution: "iconv-lite@npm:0.6.3" dependencies: - is-plain-object: ^2.0.4 - checksum: db07bc1e9de6170de70eff7001943691f05b9d1547730b11be01c0ebfe67362912ba743cf4be6fd20a5e03b4180c685dad80b7c509fe717037e3eee30ad8e84f + safer-buffer: ">= 2.1.2 < 3.0.0" + checksum: 3f60d47a5c8fc3313317edfd29a00a692cc87a19cac0159e2ce711d0ebc9019064108323b5e493625e25594f11c6236647d8e256fbe7a58f4a3b33b89e6d30bf languageName: node linkType: hard -"is-extglob@npm:^2.1.1": - version: 2.1.1 - resolution: "is-extglob@npm:2.1.1" - checksum: df033653d06d0eb567461e58a7a8c9f940bd8c22274b94bf7671ab36df5719791aae15eef6d83bbb5e23283967f2f984b8914559d4449efda578c775c4be6f85 +"idna-uts46-hx@npm:^2.3.1": + version: 2.3.1 + resolution: "idna-uts46-hx@npm:2.3.1" + dependencies: + punycode: 2.1.0 + checksum: d434c3558d2bc1090eb90f978f995101f469cb26593414ac57aa082c9352e49972b332c6e4188b9b15538172ccfeae3121e5a19b96972a97e6aeb0676d86639c languageName: node linkType: hard -"is-finite@npm:^1.0.0": - version: 1.1.0 - resolution: "is-finite@npm:1.1.0" - checksum: 532b97ed3d03e04c6bd203984d9e4ba3c0c390efee492bad5d1d1cd1802a68ab27adbd3ef6382f6312bed6c8bb1bd3e325ea79a8dc8fe080ed7a06f5f97b93e7 +"ieee754@npm:^1.1.13, ieee754@npm:^1.1.4, ieee754@npm:^1.2.1": + version: 1.2.1 + resolution: "ieee754@npm:1.2.1" + checksum: 5144c0c9815e54ada181d80a0b810221a253562422e7c6c3a60b1901154184f49326ec239d618c416c1c5945a2e197107aee8d986a3dd836b53dffefd99b5e7e languageName: node linkType: hard -"is-fn@npm:^1.0.0": - version: 1.0.0 - resolution: "is-fn@npm:1.0.0" - checksum: eeea1e536716f93a92dc1a8550b2c0909fe74bb5144d0fb6d65e0d31eb9c06c30559f69d83a9351d2288cc7293b43bc074e0fab5fae19e312ff38aa0c7672827 +"ignore@npm:^4.0.6": + version: 4.0.6 + resolution: "ignore@npm:4.0.6" + checksum: 248f82e50a430906f9ee7f35e1158e3ec4c3971451dd9f99c9bc1548261b4db2b99709f60ac6c6cac9333494384176cc4cc9b07acbe42d52ac6a09cad734d800 languageName: node linkType: hard -"is-fullwidth-code-point@npm:^1.0.0": - version: 1.0.0 - resolution: "is-fullwidth-code-point@npm:1.0.0" - dependencies: - number-is-nan: ^1.0.0 - checksum: 4d46a7465a66a8aebcc5340d3b63a56602133874af576a9ca42c6f0f4bd787a743605771c5f246db77da96605fefeffb65fc1dbe862dcc7328f4b4d03edf5a57 +"ignore@npm:^5.1.1": + version: 5.1.8 + resolution: "ignore@npm:5.1.8" + checksum: 967abadb61e2cb0e5c5e8c4e1686ab926f91bc1a4680d994b91947d3c65d04c3ae126dcdf67f08e0feeb8ff8407d453e641aeeddcc47a3a3cca359f283cf6121 languageName: node linkType: hard -"is-fullwidth-code-point@npm:^2.0.0": - version: 2.0.0 - resolution: "is-fullwidth-code-point@npm:2.0.0" - checksum: eef9c6e15f68085fec19ff6a978a6f1b8f48018fd1265035552078ee945573594933b09bbd6f562553e2a241561439f1ef5339276eba68d272001343084cfab8 +"ignore@npm:^5.2.0": + version: 5.2.4 + resolution: "ignore@npm:5.2.4" + checksum: 3d4c309c6006e2621659311783eaea7ebcd41fe4ca1d78c91c473157ad6666a57a2df790fe0d07a12300d9aac2888204d7be8d59f9aaf665b1c7fcdb432517ef languageName: node linkType: hard -"is-fullwidth-code-point@npm:^3.0.0": - version: 3.0.0 - resolution: "is-fullwidth-code-point@npm:3.0.0" - checksum: 44a30c29457c7fb8f00297bce733f0a64cd22eca270f83e58c105e0d015e45c019491a4ab2faef91ab51d4738c670daff901c799f6a700e27f7314029e99e348 +"ignore@npm:^5.3.1": + version: 5.3.2 + resolution: "ignore@npm:5.3.2" + checksum: 2acfd32a573260ea522ea0bfeff880af426d68f6831f973129e2ba7363f422923cf53aab62f8369cbf4667c7b25b6f8a3761b34ecdb284ea18e87a5262a865be languageName: node linkType: hard -"is-function@npm:^1.0.1": - version: 1.0.2 - resolution: "is-function@npm:1.0.2" - checksum: 7d564562e07b4b51359547d3ccc10fb93bb392fd1b8177ae2601ee4982a0ece86d952323fc172a9000743a3971f09689495ab78a1d49a9b14fc97a7e28521dc0 +"immutable@npm:4.2.1": + version: 4.2.1 + resolution: "immutable@npm:4.2.1" + checksum: 525bd78c4b8550df1b5f12d3bc7eb8bb3daed24f97df4018ec99a16436fc2a03fcebfcb4d3d36c86c46039292a583ea9eceb8a55704932f70a0cc5f15695b42a languageName: node linkType: hard -"is-generator-function@npm:^1.0.7": - version: 1.0.10 - resolution: "is-generator-function@npm:1.0.10" - dependencies: - has-tostringtag: ^1.0.0 - checksum: d54644e7dbaccef15ceb1e5d91d680eb5068c9ee9f9eb0a9e04173eb5542c9b51b5ab52c5537f5703e48d5fddfd376817c1ca07a84a407b7115b769d4bdde72b +"immutable@npm:^4.0.0-rc.12": + version: 4.1.0 + resolution: "immutable@npm:4.1.0" + checksum: b9bc1f14fb18eb382d48339c064b24a1f97ae4cf43102e0906c0a6e186a27afcd18b55ca4a0b63c98eefb58143e2b5ebc7755a5fb4da4a7ad84b7a6096ac5b13 languageName: node linkType: hard -"is-glob@npm:^4.0.0, is-glob@npm:^4.0.1, is-glob@npm:^4.0.3, is-glob@npm:~4.0.1": - version: 4.0.3 - resolution: "is-glob@npm:4.0.3" +"import-fresh@npm:^2.0.0": + version: 2.0.0 + resolution: "import-fresh@npm:2.0.0" dependencies: - is-extglob: ^2.1.1 - checksum: d381c1319fcb69d341cc6e6c7cd588e17cd94722d9a32dbd60660b993c4fb7d0f19438674e68dfec686d09b7c73139c9166b47597f846af387450224a8101ab4 - languageName: node - linkType: hard - -"is-hex-prefixed@npm:1.0.0": - version: 1.0.0 - resolution: "is-hex-prefixed@npm:1.0.0" - checksum: 5ac58e6e528fb029cc43140f6eeb380fad23d0041cc23154b87f7c9a1b728bcf05909974e47248fd0b7fcc11ba33cf7e58d64804883056fabd23e2b898be41de - languageName: node - linkType: hard - -"is-interactive@npm:^1.0.0": - version: 1.0.0 - resolution: "is-interactive@npm:1.0.0" - checksum: 824808776e2d468b2916cdd6c16acacebce060d844c35ca6d82267da692e92c3a16fdba624c50b54a63f38bdc4016055b6f443ce57d7147240de4f8cdabaf6f9 + caller-path: ^2.0.0 + resolve-from: ^3.0.0 + checksum: 610255f9753cc6775df00be08e9f43691aa39f7703e3636c45afe22346b8b545e600ccfe100c554607546fc8e861fa149a0d1da078c8adedeea30fff326eef79 languageName: node linkType: hard -"is-ip@npm:^3.1.0": - version: 3.1.0 - resolution: "is-ip@npm:3.1.0" +"import-fresh@npm:^3.0.0, import-fresh@npm:^3.2.1": + version: 3.3.0 + resolution: "import-fresh@npm:3.3.0" dependencies: - ip-regex: ^4.0.0 - checksum: da2c2b282407194adf2320bade0bad94be9c9d0bdab85ff45b1b62d8185f31c65dff3884519d57bf270277e5ea2046c7916a6e5a6db22fe4b7ddcdd3760f23eb + parent-module: ^1.0.0 + resolve-from: ^4.0.0 + checksum: 2cacfad06e652b1edc50be650f7ec3be08c5e5a6f6d12d035c440a42a8cc028e60a5b99ca08a77ab4d6b1346da7d971915828f33cdab730d3d42f08242d09baa languageName: node linkType: hard -"is-lambda@npm:^1.0.1": +"imul@npm:^1.0.0": version: 1.0.1 - resolution: "is-lambda@npm:1.0.1" - checksum: 93a32f01940220532e5948538699ad610d5924ac86093fcee83022252b363eb0cc99ba53ab084a04e4fb62bf7b5731f55496257a4c38adf87af9c4d352c71c35 - languageName: node - linkType: hard - -"is-negative-zero@npm:^2.0.1": - version: 2.0.1 - resolution: "is-negative-zero@npm:2.0.1" - checksum: a46f2e0cb5e16fdb8f2011ed488979386d7e68d381966682e3f4c98fc126efe47f26827912baca2d06a02a644aee458b9cba307fb389f6b161e759125db7a3b8 + resolution: "imul@npm:1.0.1" + checksum: 6c2af3d5f09e2135e14d565a2c108412b825b221eb2c881f9130467f2adccf7ae201773ae8bcf1be169e2d090567a1fdfa9cf20d3b7da7b9cecb95b920ff3e52 languageName: node linkType: hard -"is-negative-zero@npm:^2.0.2": - version: 2.0.2 - resolution: "is-negative-zero@npm:2.0.2" - checksum: f3232194c47a549da60c3d509c9a09be442507616b69454716692e37ae9f37c4dea264fb208ad0c9f3efd15a796a46b79df07c7e53c6227c32170608b809149a +"imurmurhash@npm:^0.1.4": + version: 0.1.4 + resolution: "imurmurhash@npm:0.1.4" + checksum: 7cae75c8cd9a50f57dadd77482359f659eaebac0319dd9368bcd1714f55e65badd6929ca58569da2b6494ef13fdd5598cd700b1eba23f8b79c5f19d195a3ecf7 languageName: node linkType: hard -"is-number-object@npm:^1.0.4": - version: 1.0.6 - resolution: "is-number-object@npm:1.0.6" - dependencies: - has-tostringtag: ^1.0.0 - checksum: c697704e8fc2027fc41cb81d29805de4e8b6dc9c3efee93741dbf126a8ecc8443fef85adbc581415ae7e55d325e51d0a942324ae35c829131748cce39cba55f3 +"in-publish@npm:^2.0.0": + version: 2.0.1 + resolution: "in-publish@npm:2.0.1" + bin: + in-install: in-install.js + in-publish: in-publish.js + not-in-install: not-in-install.js + not-in-publish: not-in-publish.js + checksum: 5efde2992a1e76550614a5a2c51f53669d9f3ee3a11d364de22b0c77c41de0b87c52c4c9b04375eaa276761b1944dd2b166323894d2344192328ffe85927ad38 languageName: node linkType: hard -"is-number@npm:^3.0.0": - version: 3.0.0 - resolution: "is-number@npm:3.0.0" - dependencies: - kind-of: ^3.0.2 - checksum: 0c62bf8e9d72c4dd203a74d8cfc751c746e75513380fef420cda8237e619a988ee43e678ddb23c87ac24d91ac0fe9f22e4ffb1301a50310c697e9d73ca3994e9 +"indent-string@npm:^4.0.0": + version: 4.0.0 + resolution: "indent-string@npm:4.0.0" + checksum: 824cfb9929d031dabf059bebfe08cf3137365e112019086ed3dcff6a0a7b698cb80cf67ccccde0e25b9e2d7527aa6cc1fed1ac490c752162496caba3e6699612 languageName: node linkType: hard -"is-number@npm:^7.0.0": - version: 7.0.0 - resolution: "is-number@npm:7.0.0" - checksum: 456ac6f8e0f3111ed34668a624e45315201dff921e5ac181f8ec24923b99e9f32ca1a194912dc79d539c97d33dba17dc635202ff0b2cf98326f608323276d27a +"infer-owner@npm:^1.0.4": + version: 1.0.4 + resolution: "infer-owner@npm:1.0.4" + checksum: 181e732764e4a0611576466b4b87dac338972b839920b2a8cde43642e4ed6bd54dc1fb0b40874728f2a2df9a1b097b8ff83b56d5f8f8e3927f837fdcb47d8a89 languageName: node linkType: hard -"is-plain-obj@npm:^2.1.0": - version: 2.1.0 - resolution: "is-plain-obj@npm:2.1.0" - checksum: cec9100678b0a9fe0248a81743041ed990c2d4c99f893d935545cfbc42876cbe86d207f3b895700c690ad2fa520e568c44afc1605044b535a7820c1d40e38daa +"inflight@npm:^1.0.4": + version: 1.0.6 + resolution: "inflight@npm:1.0.6" + dependencies: + once: ^1.3.0 + wrappy: 1 + checksum: f4f76aa072ce19fae87ce1ef7d221e709afb59d445e05d47fba710e85470923a75de35bfae47da6de1b18afc3ce83d70facf44cfb0aff89f0a3f45c0a0244dfd languageName: node linkType: hard -"is-plain-object@npm:^2.0.3, is-plain-object@npm:^2.0.4": +"inherits@npm:2, inherits@npm:2.0.4, inherits@npm:^2.0.1, inherits@npm:^2.0.3, inherits@npm:^2.0.4, inherits@npm:~2.0.1, inherits@npm:~2.0.3": version: 2.0.4 - resolution: "is-plain-object@npm:2.0.4" - dependencies: - isobject: ^3.0.1 - checksum: 2a401140cfd86cabe25214956ae2cfee6fbd8186809555cd0e84574f88de7b17abacb2e477a6a658fa54c6083ecbda1e6ae404c7720244cd198903848fca70ca + resolution: "inherits@npm:2.0.4" + checksum: 4a48a733847879d6cf6691860a6b1e3f0f4754176e4d71494c41f3475553768b10f84b5ce1d40fbd0e34e6bfbb864ee35858ad4dd2cf31e02fc4a154b724d7f1 languageName: node linkType: hard -"is-regex@npm:^1.0.4, is-regex@npm:^1.1.4, is-regex@npm:~1.1.4": - version: 1.1.4 - resolution: "is-regex@npm:1.1.4" - dependencies: - call-bind: ^1.0.2 - has-tostringtag: ^1.0.0 - checksum: 362399b33535bc8f386d96c45c9feb04cf7f8b41c182f54174c1a45c9abbbe5e31290bbad09a458583ff6bf3b2048672cdb1881b13289569a7c548370856a652 +"ini@npm:^1.3.5, ini@npm:~1.3.0": + version: 1.3.8 + resolution: "ini@npm:1.3.8" + checksum: dfd98b0ca3a4fc1e323e38a6c8eb8936e31a97a918d3b377649ea15bdb15d481207a0dda1021efbd86b464cae29a0d33c1d7dcaf6c5672bee17fa849bc50a1b3 languageName: node linkType: hard -"is-shared-array-buffer@npm:^1.0.1": - version: 1.0.1 - resolution: "is-shared-array-buffer@npm:1.0.1" - checksum: 2ffb92533e64e2876e6cfe6906871d28400b6f1a53130fe652ec8007bc0e5044d05e7af8e31bdc992fbba520bd92938cfbeedd0f286be92f250c7c76191c4d90 +"inquirer@npm:0.11.0": + version: 0.11.0 + resolution: "inquirer@npm:0.11.0" + dependencies: + ansi-escapes: ^1.1.0 + ansi-regex: ^2.0.0 + chalk: ^1.0.0 + cli-cursor: ^1.0.1 + cli-width: ^1.0.1 + figures: ^1.3.5 + lodash: ^3.3.1 + readline2: ^1.0.1 + run-async: ^0.1.0 + rx-lite: ^3.1.2 + strip-ansi: ^3.0.0 + through: ^2.3.6 + checksum: f36903494ccc04b1f21c1be3121c1c187582a10fd6b756e6aa3d69b33079413e37d717cd36795770a17fd4c0cec58ec8232d6af3e1452e504f97fb93b5768b51 languageName: node linkType: hard -"is-shared-array-buffer@npm:^1.0.2": - version: 1.0.2 - resolution: "is-shared-array-buffer@npm:1.0.2" +"inquirer@npm:^6.2.2": + version: 6.5.2 + resolution: "inquirer@npm:6.5.2" dependencies: - call-bind: ^1.0.2 - checksum: 9508929cf14fdc1afc9d61d723c6e8d34f5e117f0bffda4d97e7a5d88c3a8681f633a74f8e3ad1fe92d5113f9b921dc5ca44356492079612f9a247efbce7032a + ansi-escapes: ^3.2.0 + chalk: ^2.4.2 + cli-cursor: ^2.1.0 + cli-width: ^2.0.0 + external-editor: ^3.0.3 + figures: ^2.0.0 + lodash: ^4.17.12 + mute-stream: 0.0.7 + run-async: ^2.2.0 + rxjs: ^6.4.0 + string-width: ^2.1.0 + strip-ansi: ^5.1.0 + through: ^2.3.6 + checksum: 175ad4cd1ebed493b231b240185f1da5afeace5f4e8811dfa83cf55dcae59c3255eaed990aa71871b0fd31aa9dc212f43c44c50ed04fb529364405e72f484d28 languageName: node linkType: hard -"is-stream@npm:^1.0.1, is-stream@npm:^1.1.0": - version: 1.1.0 - resolution: "is-stream@npm:1.1.0" - checksum: 063c6bec9d5647aa6d42108d4c59723d2bd4ae42135a2d4db6eadbd49b7ea05b750fd69d279e5c7c45cf9da753ad2c00d8978be354d65aa9f6bb434969c6a2ae +"interface-datastore@npm:^6.0.2": + version: 6.1.1 + resolution: "interface-datastore@npm:6.1.1" + dependencies: + interface-store: ^2.0.2 + nanoid: ^3.0.2 + uint8arrays: ^3.0.0 + checksum: a0388adabf029be229bbfce326bbe64fd3353373512e7e6ed4283e06710bfa141db118e3536f8535a65016a0abeec631b888d42790b00637879d6ae56cf728cd languageName: node linkType: hard -"is-stream@npm:^2.0.0": - version: 2.0.1 - resolution: "is-stream@npm:2.0.1" - checksum: b8e05ccdf96ac330ea83c12450304d4a591f9958c11fd17bed240af8d5ffe08aedafa4c0f4cfccd4d28dc9d4d129daca1023633d5c11601a6cbc77521f6fae66 +"interface-store@npm:^2.0.2": + version: 2.0.2 + resolution: "interface-store@npm:2.0.2" + checksum: 0e80adb1de9ff57687cfa1b08499702b72cacf33a7e0320ac7781989f3685d73f2a84996358f540250229afa19c7acebf03085087762f718035622ea6a1a5b8a languageName: node linkType: hard -"is-string@npm:^1.0.5, is-string@npm:^1.0.7": - version: 1.0.7 - resolution: "is-string@npm:1.0.7" +"internal-slot@npm:^1.0.3": + version: 1.0.3 + resolution: "internal-slot@npm:1.0.3" dependencies: - has-tostringtag: ^1.0.0 - checksum: 323b3d04622f78d45077cf89aab783b2f49d24dc641aa89b5ad1a72114cfeff2585efc8c12ef42466dff32bde93d839ad321b26884cf75e5a7892a938b089989 + get-intrinsic: ^1.1.0 + has: ^1.0.3 + side-channel: ^1.0.4 + checksum: 1944f92e981e47aebc98a88ff0db579fd90543d937806104d0b96557b10c1f170c51fb777b97740a8b6ddeec585fca8c39ae99fd08a8e058dfc8ab70937238bf languageName: node linkType: hard -"is-symbol@npm:^1.0.2, is-symbol@npm:^1.0.3": - version: 1.0.4 - resolution: "is-symbol@npm:1.0.4" +"internal-slot@npm:^1.0.5": + version: 1.0.5 + resolution: "internal-slot@npm:1.0.5" dependencies: - has-symbols: ^1.0.2 - checksum: 92805812ef590738d9de49d677cd17dfd486794773fb6fa0032d16452af46e9b91bb43ffe82c983570f015b37136f4b53b28b8523bfb10b0ece7a66c31a54510 + get-intrinsic: ^1.2.0 + has: ^1.0.3 + side-channel: ^1.0.4 + checksum: 97e84046bf9e7574d0956bd98d7162313ce7057883b6db6c5c7b5e5f05688864b0978ba07610c726d15d66544ffe4b1050107d93f8a39ebc59b15d8b429b497a languageName: node linkType: hard -"is-typed-array@npm:^1.1.10, is-typed-array@npm:^1.1.12": - version: 1.1.12 - resolution: "is-typed-array@npm:1.1.12" - dependencies: - which-typed-array: ^1.1.11 - checksum: 4c89c4a3be07186caddadf92197b17fda663a9d259ea0d44a85f171558270d36059d1c386d34a12cba22dfade5aba497ce22778e866adc9406098c8fc4771796 +"interpret@npm:^1.0.0": + version: 1.4.0 + resolution: "interpret@npm:1.4.0" + checksum: 2e5f51268b5941e4a17e4ef0575bc91ed0ab5f8515e3cf77486f7c14d13f3010df9c0959f37063dcc96e78d12dc6b0bb1b9e111cdfe69771f4656d2993d36155 languageName: node linkType: hard -"is-typed-array@npm:^1.1.3, is-typed-array@npm:^1.1.9": - version: 1.1.9 - resolution: "is-typed-array@npm:1.1.9" +"invariant@npm:2, invariant@npm:^2.2.2": + version: 2.2.4 + resolution: "invariant@npm:2.2.4" dependencies: - available-typed-arrays: ^1.0.5 - call-bind: ^1.0.2 - es-abstract: ^1.20.0 - for-each: ^0.3.3 - has-tostringtag: ^1.0.0 - checksum: 11910f1e58755fef43bf0074e52fa5b932bf101ec65d613e0a83d40e8e4c6e3f2ee142d624ebc7624c091d3bbe921131f8db7d36ecbbb71909f2fe310c1faa65 + loose-envify: ^1.0.0 + checksum: cc3182d793aad82a8d1f0af697b462939cb46066ec48bbf1707c150ad5fad6406137e91a262022c269702e01621f35ef60269f6c0d7fd178487959809acdfb14 languageName: node linkType: hard -"is-typedarray@npm:^1.0.0, is-typedarray@npm:~1.0.0": - version: 1.0.0 - resolution: "is-typedarray@npm:1.0.0" - checksum: 3508c6cd0a9ee2e0df2fa2e9baabcdc89e911c7bd5cf64604586697212feec525aa21050e48affb5ffc3df20f0f5d2e2cf79b08caa64e1ccc9578e251763aef7 +"io-ts@npm:1.10.4": + version: 1.10.4 + resolution: "io-ts@npm:1.10.4" + dependencies: + fp-ts: ^1.0.0 + checksum: 619134006778f7ca42693716ade7fc1a383079e7848bbeabc67a0e4ac9139cda6b2a88a052d539ab7d554033ee2ffe4dab5cb96b958c83fee2dff73d23f03e88 languageName: node linkType: hard -"is-unicode-supported@npm:^0.1.0": - version: 0.1.0 - resolution: "is-unicode-supported@npm:0.1.0" - checksum: a2aab86ee7712f5c2f999180daaba5f361bdad1efadc9610ff5b8ab5495b86e4f627839d085c6530363c6d6d4ecbde340fb8e54bdb83da4ba8e0865ed5513c52 +"ip-regex@npm:^4.0.0": + version: 4.3.0 + resolution: "ip-regex@npm:4.3.0" + checksum: 7ff904b891221b1847f3fdf3dbb3e6a8660dc39bc283f79eb7ed88f5338e1a3d1104b779bc83759159be266249c59c2160e779ee39446d79d4ed0890dfd06f08 languageName: node linkType: hard -"is-url@npm:^1.2.4": - version: 1.2.4 - resolution: "is-url@npm:1.2.4" - checksum: 100e74b3b1feab87a43ef7653736e88d997eb7bd32e71fd3ebc413e58c1cbe56269699c776aaea84244b0567f2a7d68dfaa512a062293ed2f9fdecb394148432 +"ip@npm:^1.1.5": + version: 1.1.5 + resolution: "ip@npm:1.1.5" + checksum: 30133981f082a060a32644f6a7746e9ba7ac9e2bc07ecc8bbdda3ee8ca9bec1190724c390e45a1ee7695e7edfd2a8f7dda2c104ec5f7ac5068c00648504c7e5a languageName: node linkType: hard -"is-utf8@npm:^0.2.0": - version: 0.2.1 - resolution: "is-utf8@npm:0.2.1" - checksum: 167ccd2be869fc228cc62c1a28df4b78c6b5485d15a29027d3b5dceb09b383e86a3522008b56dcac14b592b22f0a224388718c2505027a994fd8471465de54b3 +"ipaddr.js@npm:1.9.1": + version: 1.9.1 + resolution: "ipaddr.js@npm:1.9.1" + checksum: f88d3825981486f5a1942414c8d77dd6674dd71c065adcfa46f578d677edcb99fda25af42675cb59db492fdf427b34a5abfcde3982da11a8fd83a500b41cfe77 languageName: node linkType: hard -"is-weakref@npm:^1.0.1": - version: 1.0.1 - resolution: "is-weakref@npm:1.0.1" +"ipfs-core-types@npm:^0.9.0": + version: 0.9.0 + resolution: "ipfs-core-types@npm:0.9.0" dependencies: - call-bind: ^1.0.0 - checksum: fdafb7b955671dd2f9658ff47c86e4025c0650fc68a3542a40e5a75898a763b1abd6b1e1f9f13207eed49541cdd76af67d73c44989ea358b201b70274cf8f6c1 + interface-datastore: ^6.0.2 + multiaddr: ^10.0.0 + multiformats: ^9.4.13 + checksum: 22db8e039348dc372c99b45a87ce8dce81e15fa710cee410c1731004d528e0bd0da96b5a4c5571d501313fae93316af3b902c2220c486d2fade2e53f07a7d17b languageName: node linkType: hard -"is-weakref@npm:^1.0.2": - version: 1.0.2 - resolution: "is-weakref@npm:1.0.2" +"ipfs-core-utils@npm:^0.13.0": + version: 0.13.0 + resolution: "ipfs-core-utils@npm:0.13.0" dependencies: - call-bind: ^1.0.2 - checksum: 95bd9a57cdcb58c63b1c401c60a474b0f45b94719c30f548c891860f051bc2231575c290a6b420c6bc6e7ed99459d424c652bd5bf9a1d5259505dc35b4bf83de + any-signal: ^2.1.2 + blob-to-it: ^1.0.1 + browser-readablestream-to-it: ^1.0.1 + debug: ^4.1.1 + err-code: ^3.0.1 + ipfs-core-types: ^0.9.0 + ipfs-unixfs: ^6.0.3 + ipfs-utils: ^9.0.2 + it-all: ^1.0.4 + it-map: ^1.0.4 + it-peekable: ^1.0.2 + it-to-stream: ^1.0.0 + merge-options: ^3.0.4 + multiaddr: ^10.0.0 + multiaddr-to-uri: ^8.0.0 + multiformats: ^9.4.13 + nanoid: ^3.1.23 + parse-duration: ^1.0.0 + timeout-abort-controller: ^2.0.0 + uint8arrays: ^3.0.0 + checksum: af46717a69cf2e4f1bfbd77c7c1951eaa8b9619bdb888ca971849dc2d2468aceb0238e2f47ae45568478b2ceb1428ae7061239afc92aac06691f7bea9e21e4eb languageName: node linkType: hard -"is-windows@npm:^1.0.2": - version: 1.0.2 - resolution: "is-windows@npm:1.0.2" - checksum: 438b7e52656fe3b9b293b180defb4e448088e7023a523ec21a91a80b9ff8cdb3377ddb5b6e60f7c7de4fa8b63ab56e121b6705fe081b3cf1b828b0a380009ad7 +"ipfs-http-client@npm:55.0.0": + version: 55.0.0 + resolution: "ipfs-http-client@npm:55.0.0" + dependencies: + "@ipld/dag-cbor": ^7.0.0 + "@ipld/dag-json": ^8.0.1 + "@ipld/dag-pb": ^2.1.3 + abort-controller: ^3.0.0 + any-signal: ^2.1.2 + debug: ^4.1.1 + err-code: ^3.0.1 + ipfs-core-types: ^0.9.0 + ipfs-core-utils: ^0.13.0 + ipfs-utils: ^9.0.2 + it-first: ^1.0.6 + it-last: ^1.0.4 + merge-options: ^3.0.4 + multiaddr: ^10.0.0 + multiformats: ^9.4.13 + native-abort-controller: ^1.0.3 + parse-duration: ^1.0.0 + stream-to-it: ^0.2.2 + uint8arrays: ^3.0.0 + checksum: b44394475dd9f6ef2e68cf22fb5bacf93c1a8967712f12a56baf9e90f183d625569bcabfe2e7c0d1cd2f0a2eed577ab8282f5a737552faf83d3b8a82d7910494 languageName: node linkType: hard -"is-wsl@npm:^2.1.1, is-wsl@npm:^2.2.0": - version: 2.2.0 - resolution: "is-wsl@npm:2.2.0" +"ipfs-unixfs@npm:^6.0.3": + version: 6.0.9 + resolution: "ipfs-unixfs@npm:6.0.9" dependencies: - is-docker: ^2.0.0 - checksum: 20849846ae414997d290b75e16868e5261e86ff5047f104027026fd61d8b5a9b0b3ade16239f35e1a067b3c7cc02f70183cb661010ed16f4b6c7c93dad1b19d8 + err-code: ^3.0.1 + protobufjs: ^6.10.2 + checksum: 025d852c3cfb09b813b35f7a4f7a06bd0ff904f88b35cdf54c6ea1eb021f1597ab9c2739adabbae9cfe645a2323598bd7974ff4a8898701bc4ba92842bf21736 languageName: node linkType: hard -"isarray@npm:0.0.1": - version: 0.0.1 - resolution: "isarray@npm:0.0.1" - checksum: 49191f1425681df4a18c2f0f93db3adb85573bcdd6a4482539d98eac9e705d8961317b01175627e860516a2fc45f8f9302db26e5a380a97a520e272e2a40a8d4 +"ipfs-utils@npm:^9.0.2": + version: 9.0.14 + resolution: "ipfs-utils@npm:9.0.14" + dependencies: + any-signal: ^3.0.0 + browser-readablestream-to-it: ^1.0.0 + buffer: ^6.0.1 + electron-fetch: ^1.7.2 + err-code: ^3.0.1 + is-electron: ^2.2.0 + iso-url: ^1.1.5 + it-all: ^1.0.4 + it-glob: ^1.0.1 + it-to-stream: ^1.0.0 + merge-options: ^3.0.4 + nanoid: ^3.1.20 + native-fetch: ^3.0.0 + node-fetch: ^2.6.8 + react-native-fetch-api: ^3.0.0 + stream-to-it: ^0.2.2 + checksum: 08108e03ea7b90e0fa11b76a4e24bd29d7e027c603494b53c1cc37b367fb559eaeea7b0f10b2e83ee419d50cdcb4d8105febdf185cab75c7e55afd4c8ed51aba languageName: node linkType: hard -"isarray@npm:1.0.0, isarray@npm:^1.0.0, isarray@npm:~1.0.0": - version: 1.0.0 - resolution: "isarray@npm:1.0.0" - checksum: f032df8e02dce8ec565cf2eb605ea939bdccea528dbcf565cdf92bfa2da9110461159d86a537388ef1acef8815a330642d7885b29010e8f7eac967c9993b65ab +"is-arguments@npm:^1.0.4": + version: 1.1.1 + resolution: "is-arguments@npm:1.1.1" + dependencies: + call-bind: ^1.0.2 + has-tostringtag: ^1.0.0 + checksum: 7f02700ec2171b691ef3e4d0e3e6c0ba408e8434368504bb593d0d7c891c0dbfda6d19d30808b904a6cb1929bca648c061ba438c39f296c2a8ca083229c49f27 languageName: node linkType: hard -"isarray@npm:^2.0.5": - version: 2.0.5 - resolution: "isarray@npm:2.0.5" - checksum: bd5bbe4104438c4196ba58a54650116007fa0262eccef13a4c55b2e09a5b36b59f1e75b9fcc49883dd9d4953892e6fc007eef9e9155648ceea036e184b0f930a +"is-array-buffer@npm:^3.0.1, is-array-buffer@npm:^3.0.2": + version: 3.0.2 + resolution: "is-array-buffer@npm:3.0.2" + dependencies: + call-bind: ^1.0.2 + get-intrinsic: ^1.2.0 + is-typed-array: ^1.1.10 + checksum: dcac9dda66ff17df9cabdc58214172bf41082f956eab30bb0d86bc0fab1e44b690fc8e1f855cf2481245caf4e8a5a006a982a71ddccec84032ed41f9d8da8c14 languageName: node linkType: hard -"isexe@npm:^2.0.0": - version: 2.0.0 - resolution: "isexe@npm:2.0.0" - checksum: 26bf6c5480dda5161c820c5b5c751ae1e766c587b1f951ea3fcfc973bafb7831ae5b54a31a69bd670220e42e99ec154475025a468eae58ea262f813fdc8d1c62 +"is-arrayish@npm:^0.2.1": + version: 0.2.1 + resolution: "is-arrayish@npm:0.2.1" + checksum: eef4417e3c10e60e2c810b6084942b3ead455af16c4509959a27e490e7aee87cfb3f38e01bbde92220b528a0ee1a18d52b787e1458ee86174d8c7f0e58cd488f languageName: node linkType: hard -"iso-url@npm:^1.1.5": - version: 1.2.1 - resolution: "iso-url@npm:1.2.1" - checksum: 1af98c4ed6a39598407fd8c3c13e997c978985f477af2be3390d2aa3e422b4b5992ffbb0dac68656b165c71850fff748ac1309d29d4f2a728707d76bf0f98557 +"is-bigint@npm:^1.0.1": + version: 1.0.4 + resolution: "is-bigint@npm:1.0.4" + dependencies: + has-bigints: ^1.0.1 + checksum: c56edfe09b1154f8668e53ebe8252b6f185ee852a50f9b41e8d921cb2bed425652049fbe438723f6cb48a63ca1aa051e948e7e401e093477c99c84eba244f666 languageName: node linkType: hard -"isobject@npm:^2.0.0": +"is-binary-path@npm:~2.1.0": version: 2.1.0 - resolution: "isobject@npm:2.1.0" + resolution: "is-binary-path@npm:2.1.0" dependencies: - isarray: 1.0.0 - checksum: 811c6f5a866877d31f0606a88af4a45f282544de886bf29f6a34c46616a1ae2ed17076cc6bf34c0128f33eecf7e1fcaa2c82cf3770560d3e26810894e96ae79f - languageName: node - linkType: hard - -"isobject@npm:^3.0.0, isobject@npm:^3.0.1": - version: 3.0.1 - resolution: "isobject@npm:3.0.1" - checksum: db85c4c970ce30693676487cca0e61da2ca34e8d4967c2e1309143ff910c207133a969f9e4ddb2dc6aba670aabce4e0e307146c310350b298e74a31f7d464703 + binary-extensions: ^2.0.0 + checksum: 84192eb88cff70d320426f35ecd63c3d6d495da9d805b19bc65b518984b7c0760280e57dbf119b7e9be6b161784a5a673ab2c6abe83abb5198a432232ad5b35c languageName: node linkType: hard -"isomorphic-unfetch@npm:^3.0.0": - version: 3.1.0 - resolution: "isomorphic-unfetch@npm:3.1.0" +"is-boolean-object@npm:^1.1.0": + version: 1.1.2 + resolution: "is-boolean-object@npm:1.1.2" dependencies: - node-fetch: ^2.6.1 - unfetch: ^4.2.0 - checksum: 82b92fe4ec2823a81ab0fc0d11bd94d710e6f9a940d56b3cba31896d4345ec9ffc7949f4ff31ebcae84f6b95f7ebf3474c4c7452b834eb4078ea3f2c37e459c5 - languageName: node - linkType: hard - -"isomorphic-ws@npm:^4.0.1": - version: 4.0.1 - resolution: "isomorphic-ws@npm:4.0.1" - peerDependencies: - ws: "*" - checksum: d7190eadefdc28bdb93d67b5f0c603385aaf87724fa2974abb382ac1ec9756ed2cfb27065cbe76122879c2d452e2982bc4314317f3d6c737ddda6c047328771a - languageName: node - linkType: hard - -"isows@npm:1.0.7": - version: 1.0.7 - resolution: "isows@npm:1.0.7" - peerDependencies: - ws: "*" - checksum: 044b949b369872882af07b60b613b5801ae01b01a23b5b72b78af80c8103bbeed38352c3e8ceff13a7834bc91fd2eb41cf91ec01d59a041d8705680e6b0ec546 + call-bind: ^1.0.2 + has-tostringtag: ^1.0.0 + checksum: c03b23dbaacadc18940defb12c1c0e3aaece7553ef58b162a0f6bba0c2a7e1551b59f365b91e00d2dbac0522392d576ef322628cb1d036a0fe51eb466db67222 languageName: node linkType: hard -"isstream@npm:~0.1.2": - version: 0.1.2 - resolution: "isstream@npm:0.1.2" - checksum: 1eb2fe63a729f7bdd8a559ab552c69055f4f48eb5c2f03724430587c6f450783c8f1cd936c1c952d0a927925180fcc892ebd5b174236cf1065d4bd5bdb37e963 +"is-buffer@npm:~2.0.3": + version: 2.0.5 + resolution: "is-buffer@npm:2.0.5" + checksum: 764c9ad8b523a9f5a32af29bdf772b08eb48c04d2ad0a7240916ac2688c983bf5f8504bf25b35e66240edeb9d9085461f9b5dae1f3d2861c6b06a65fe983de42 languageName: node linkType: hard -"it-all@npm:^1.0.4": - version: 1.0.6 - resolution: "it-all@npm:1.0.6" - checksum: 7ca9a528c08ebe2fc8a3c93a41409219d18325ed31fedb9834ebac2822f0b2a96d7abcb6cbfa092114ab4d5f08951e694c7a2c3929ce4b5300769e710ae665db +"is-callable@npm:^1.1.3, is-callable@npm:^1.2.7": + version: 1.2.7 + resolution: "is-callable@npm:1.2.7" + checksum: 61fd57d03b0d984e2ed3720fb1c7a897827ea174bd44402878e059542ea8c4aeedee0ea0985998aa5cc2736b2fa6e271c08587addb5b3959ac52cf665173d1ac languageName: node linkType: hard -"it-first@npm:^1.0.6": - version: 1.0.7 - resolution: "it-first@npm:1.0.7" - checksum: 0c9106d29120f02e68a08118de328437fb44c966385635d672684d4f0321ee22ca470a30f390132bdb454da0d4d3abb82c796dad8e391a827f1a3446711c7685 +"is-callable@npm:^1.1.4, is-callable@npm:^1.2.4": + version: 1.2.4 + resolution: "is-callable@npm:1.2.4" + checksum: 1a28d57dc435797dae04b173b65d6d1e77d4f16276e9eff973f994eadcfdc30a017e6a597f092752a083c1103cceb56c91e3dadc6692fedb9898dfaba701575f languageName: node linkType: hard -"it-glob@npm:^1.0.1": - version: 1.0.2 - resolution: "it-glob@npm:1.0.2" +"is-core-module@npm:^2.2.0, is-core-module@npm:^2.7.0": + version: 2.8.0 + resolution: "is-core-module@npm:2.8.0" dependencies: - "@types/minimatch": ^3.0.4 - minimatch: ^3.0.4 - checksum: 629e7b66510006041df98882acfd73ac785836d51fc3ffa5c83c7099f931b3287a64c5a3772e7c1e46b63f1d511a9222f5b637c50f1c738222b46d104ff2e91c + has: ^1.0.3 + checksum: f8b52714891e1a6c6577fcb8d5e057bab064a7a30954aab6beb5092e311473eb8da57afd334de4981dc32409ffca998412efc3a2edceb9e397cef6098d21dd91 languageName: node linkType: hard -"it-last@npm:^1.0.4": - version: 1.0.6 - resolution: "it-last@npm:1.0.6" - checksum: bc7b68ddd6cae902f0095d0c7ccb0078abdfa41fbf55862a9df9e30ae74be08282b5b3d21f40e6103af0d202144974e216d3c44f3e8f93c2c3f890322b02fcfa +"is-date-object@npm:^1.0.1": + version: 1.0.5 + resolution: "is-date-object@npm:1.0.5" + dependencies: + has-tostringtag: ^1.0.0 + checksum: baa9077cdf15eb7b58c79398604ca57379b2fc4cf9aa7a9b9e295278648f628c9b201400c01c5e0f7afae56507d741185730307cbe7cad3b9f90a77e5ee342fc languageName: node linkType: hard -"it-map@npm:^1.0.4": - version: 1.0.6 - resolution: "it-map@npm:1.0.6" - checksum: 5eb9da69e5d58624c79cea13dd8eeffe8a1ab6a28a527ac4d0301304279ffbe8da94faf50aa269e2a1630c94dc30a6bfe7a135bfb0c7e887216efad7c41a9f52 +"is-directory@npm:^0.3.1": + version: 0.3.1 + resolution: "is-directory@npm:0.3.1" + checksum: dce9a9d3981e38f2ded2a80848734824c50ee8680cd09aa477bef617949715cfc987197a2ca0176c58a9fb192a1a0d69b535c397140d241996a609d5906ae524 languageName: node linkType: hard -"it-peekable@npm:^1.0.2": - version: 1.0.3 - resolution: "it-peekable@npm:1.0.3" - checksum: 6e9d68cbf582e301f191b8ad2660957c12c8100804a298fd5732ee35f2dd466a6af64d88d91343f2614675b4d4fb546618335303e9356659a9a0868c08b1ca54 +"is-docker@npm:^2.0.0": + version: 2.2.1 + resolution: "is-docker@npm:2.2.1" + bin: + is-docker: cli.js + checksum: 3fef7ddbf0be25958e8991ad941901bf5922ab2753c46980b60b05c1bf9c9c2402d35e6dc32e4380b980ef5e1970a5d9d5e5aa2e02d77727c3b6b5e918474c56 languageName: node linkType: hard -"it-to-stream@npm:^1.0.0": - version: 1.0.0 - resolution: "it-to-stream@npm:1.0.0" - dependencies: - buffer: ^6.0.3 - fast-fifo: ^1.0.0 - get-iterator: ^1.0.2 - p-defer: ^3.0.0 - p-fifo: ^1.0.0 - readable-stream: ^3.6.0 - checksum: e0c5a3f3c90d4bc52686217865b8fa202f64bd3af493dec0fdacd58b4237166fb68935ff2823ed0a16414ba5becb9a5fb8c98f3ec99584789776d7277c1d129f +"is-electron@npm:^2.2.0": + version: 2.2.0 + resolution: "is-electron@npm:2.2.0" + checksum: 79e497bd5077018ed2e243c1524a2af21d9cac56962a1aa09284450f315626ca41b184f5599c9ab6526245d0cd8fe4abe962817fde48100f632c104ad5d03560 languageName: node linkType: hard -"jake@npm:^10.6.1, jake@npm:^10.8.5": - version: 10.8.7 - resolution: "jake@npm:10.8.7" - dependencies: - async: ^3.2.3 - chalk: ^4.0.2 - filelist: ^1.0.4 - minimatch: ^3.1.2 - bin: - jake: bin/cli.js - checksum: a23fd2273fb13f0d0d845502d02c791fd55ef5c6a2d207df72f72d8e1eac6d2b8ffa6caf660bc8006b3242e0daaa88a3ecc600194d72b5c6016ad56e9cd43553 +"is-extglob@npm:^2.1.1": + version: 2.1.1 + resolution: "is-extglob@npm:2.1.1" + checksum: df033653d06d0eb567461e58a7a8c9f940bd8c22274b94bf7671ab36df5719791aae15eef6d83bbb5e23283967f2f984b8914559d4449efda578c775c4be6f85 languageName: node linkType: hard -"jayson@npm:4.0.0": - version: 4.0.0 - resolution: "jayson@npm:4.0.0" +"is-fullwidth-code-point@npm:^1.0.0": + version: 1.0.0 + resolution: "is-fullwidth-code-point@npm:1.0.0" dependencies: - "@types/connect": ^3.4.33 - "@types/node": ^12.12.54 - "@types/ws": ^7.4.4 - JSONStream: ^1.3.5 - commander: ^2.20.3 - delay: ^5.0.0 - es6-promisify: ^5.0.0 - eyes: ^0.1.8 - isomorphic-ws: ^4.0.1 - json-stringify-safe: ^5.0.1 - uuid: ^8.3.2 - ws: ^7.4.5 - bin: - jayson: bin/jayson.js - checksum: 39eed3dc8d0e35320b0234f0faf7d6195b0cdc6940ec969f603a3ea14de8da98f2bd2775e3b982fe1ee6de63e66428fbf322d426e659fa25ea86c8ac92c8710d - languageName: node - linkType: hard - -"js-cookie@npm:^2.2.1": - version: 2.2.1 - resolution: "js-cookie@npm:2.2.1" - checksum: 9b1fb980a1c5e624fd4b28ea4867bb30c71e04c4484bb3a42766344c533faa684de9498e443425479ec68609e96e27b60614bfe354877c449c631529b6d932f2 + number-is-nan: ^1.0.0 + checksum: 4d46a7465a66a8aebcc5340d3b63a56602133874af576a9ca42c6f0f4bd787a743605771c5f246db77da96605fefeffb65fc1dbe862dcc7328f4b4d03edf5a57 languageName: node linkType: hard -"js-sdsl@npm:^4.1.4": - version: 4.4.1 - resolution: "js-sdsl@npm:4.4.1" - checksum: ba445b53531f2f353f8f66ed8c7edc7942c9bac68707161aa70528fa8ee9a89805d170cff171aa40bdac1aed5dfe97dce6f929e6f759a487ed619387a5ea1365 +"is-fullwidth-code-point@npm:^2.0.0": + version: 2.0.0 + resolution: "is-fullwidth-code-point@npm:2.0.0" + checksum: eef9c6e15f68085fec19ff6a978a6f1b8f48018fd1265035552078ee945573594933b09bbd6f562553e2a241561439f1ef5339276eba68d272001343084cfab8 languageName: node linkType: hard -"js-sha3@npm:0.5.7, js-sha3@npm:^0.5.7": - version: 0.5.7 - resolution: "js-sha3@npm:0.5.7" - checksum: 973a28ea4b26cc7f12d2ab24f796e24ee4a71eef45a6634a052f6eb38cf8b2333db798e896e6e094ea6fa4dfe8e42a2a7942b425cf40da3f866623fd05bb91ea +"is-fullwidth-code-point@npm:^3.0.0": + version: 3.0.0 + resolution: "is-fullwidth-code-point@npm:3.0.0" + checksum: 44a30c29457c7fb8f00297bce733f0a64cd22eca270f83e58c105e0d015e45c019491a4ab2faef91ab51d4738c670daff901c799f6a700e27f7314029e99e348 languageName: node linkType: hard -"js-sha3@npm:0.8.0, js-sha3@npm:^0.8.0": - version: 0.8.0 - resolution: "js-sha3@npm:0.8.0" - checksum: 75df77c1fc266973f06cce8309ce010e9e9f07ec35ab12022ed29b7f0d9c8757f5a73e1b35aa24840dced0dea7059085aa143d817aea9e188e2a80d569d9adce +"is-function@npm:^1.0.1": + version: 1.0.2 + resolution: "is-function@npm:1.0.2" + checksum: 7d564562e07b4b51359547d3ccc10fb93bb392fd1b8177ae2601ee4982a0ece86d952323fc172a9000743a3971f09689495ab78a1d49a9b14fc97a7e28521dc0 languageName: node linkType: hard -"js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0": - version: 4.0.0 - resolution: "js-tokens@npm:4.0.0" - checksum: 8a95213a5a77deb6cbe94d86340e8d9ace2b93bc367790b260101d2f36a2eaf4e4e22d9fa9cf459b38af3a32fb4190e638024cf82ec95ef708680e405ea7cc78 +"is-generator-function@npm:^1.0.7": + version: 1.0.10 + resolution: "is-generator-function@npm:1.0.10" + dependencies: + has-tostringtag: ^1.0.0 + checksum: d54644e7dbaccef15ceb1e5d91d680eb5068c9ee9f9eb0a9e04173eb5542c9b51b5ab52c5537f5703e48d5fddfd376817c1ca07a84a407b7115b769d4bdde72b languageName: node linkType: hard -"js-tokens@npm:^3.0.2": - version: 3.0.2 - resolution: "js-tokens@npm:3.0.2" - checksum: ff24cf90e6e4ac446eba56e604781c1aaf3bdaf9b13a00596a0ebd972fa3b25dc83c0f0f67289c33252abb4111e0d14e952a5d9ffb61f5c22532d555ebd8d8a9 +"is-glob@npm:^4.0.0, is-glob@npm:^4.0.1, is-glob@npm:^4.0.3, is-glob@npm:~4.0.1": + version: 4.0.3 + resolution: "is-glob@npm:4.0.3" + dependencies: + is-extglob: ^2.1.1 + checksum: d381c1319fcb69d341cc6e6c7cd588e17cd94722d9a32dbd60660b993c4fb7d0f19438674e68dfec686d09b7c73139c9166b47597f846af387450224a8101ab4 languageName: node linkType: hard -"js-yaml@npm:3.13.1": - version: 3.13.1 - resolution: "js-yaml@npm:3.13.1" - dependencies: - argparse: ^1.0.7 - esprima: ^4.0.0 - bin: - js-yaml: bin/js-yaml.js - checksum: 7511b764abb66d8aa963379f7d2a404f078457d106552d05a7b556d204f7932384e8477513c124749fa2de52eb328961834562bd09924902c6432e40daa408bc +"is-hex-prefixed@npm:1.0.0": + version: 1.0.0 + resolution: "is-hex-prefixed@npm:1.0.0" + checksum: 5ac58e6e528fb029cc43140f6eeb380fad23d0041cc23154b87f7c9a1b728bcf05909974e47248fd0b7fcc11ba33cf7e58d64804883056fabd23e2b898be41de languageName: node linkType: hard -"js-yaml@npm:3.14.1, js-yaml@npm:3.x, js-yaml@npm:^3.12.0, js-yaml@npm:^3.13.0, js-yaml@npm:^3.13.1, js-yaml@npm:^3.14.1": - version: 3.14.1 - resolution: "js-yaml@npm:3.14.1" - dependencies: - argparse: ^1.0.7 - esprima: ^4.0.0 - bin: - js-yaml: bin/js-yaml.js - checksum: bef146085f472d44dee30ec34e5cf36bf89164f5d585435a3d3da89e52622dff0b188a580e4ad091c3341889e14cb88cac6e4deb16dc5b1e9623bb0601fc255c +"is-interactive@npm:^1.0.0": + version: 1.0.0 + resolution: "is-interactive@npm:1.0.0" + checksum: 824808776e2d468b2916cdd6c16acacebce060d844c35ca6d82267da692e92c3a16fdba624c50b54a63f38bdc4016055b6f443ce57d7147240de4f8cdabaf6f9 languageName: node linkType: hard -"js-yaml@npm:4.1.0, js-yaml@npm:^4.1.0": - version: 4.1.0 - resolution: "js-yaml@npm:4.1.0" +"is-ip@npm:^3.1.0": + version: 3.1.0 + resolution: "is-ip@npm:3.1.0" dependencies: - argparse: ^2.0.1 - bin: - js-yaml: bin/js-yaml.js - checksum: c7830dfd456c3ef2c6e355cc5a92e6700ceafa1d14bba54497b34a99f0376cecbb3e9ac14d3e5849b426d5a5140709a66237a8c991c675431271c4ce5504151a + ip-regex: ^4.0.0 + checksum: da2c2b282407194adf2320bade0bad94be9c9d0bdab85ff45b1b62d8185f31c65dff3884519d57bf270277e5ea2046c7916a6e5a6db22fe4b7ddcdd3760f23eb languageName: node linkType: hard -"jsbn@npm:~0.1.0": - version: 0.1.1 - resolution: "jsbn@npm:0.1.1" - checksum: e5ff29c1b8d965017ef3f9c219dacd6e40ad355c664e277d31246c90545a02e6047018c16c60a00f36d561b3647215c41894f5d869ada6908a2e0ce4200c88f2 +"is-lambda@npm:^1.0.1": + version: 1.0.1 + resolution: "is-lambda@npm:1.0.1" + checksum: 93a32f01940220532e5948538699ad610d5924ac86093fcee83022252b363eb0cc99ba53ab084a04e4fb62bf7b5731f55496257a4c38adf87af9c4d352c71c35 languageName: node linkType: hard -"jsesc@npm:^1.3.0": - version: 1.3.0 - resolution: "jsesc@npm:1.3.0" - bin: - jsesc: bin/jsesc - checksum: 9384cc72bf8ef7f2eb75fea64176b8b0c1c5e77604854c72cb4670b7072e112e3baaa69ef134be98cb078834a7812b0bfe676ad441ccd749a59427f5ed2127f1 +"is-negative-zero@npm:^2.0.1": + version: 2.0.1 + resolution: "is-negative-zero@npm:2.0.1" + checksum: a46f2e0cb5e16fdb8f2011ed488979386d7e68d381966682e3f4c98fc126efe47f26827912baca2d06a02a644aee458b9cba307fb389f6b161e759125db7a3b8 languageName: node linkType: hard -"jsesc@npm:~0.5.0": - version: 0.5.0 - resolution: "jsesc@npm:0.5.0" - bin: - jsesc: bin/jsesc - checksum: b8b44cbfc92f198ad972fba706ee6a1dfa7485321ee8c0b25f5cedd538dcb20cde3197de16a7265430fce8277a12db066219369e3d51055038946039f6e20e17 +"is-negative-zero@npm:^2.0.2": + version: 2.0.2 + resolution: "is-negative-zero@npm:2.0.2" + checksum: f3232194c47a549da60c3d509c9a09be442507616b69454716692e37ae9f37c4dea264fb208ad0c9f3efd15a796a46b79df07c7e53c6227c32170608b809149a languageName: node linkType: hard -"json-buffer@npm:3.0.0": - version: 3.0.0 - resolution: "json-buffer@npm:3.0.0" - checksum: 0cecacb8025370686a916069a2ff81f7d55167421b6aa7270ee74e244012650dd6bce22b0852202ea7ff8624fce50ff0ec1bdf95914ccb4553426e290d5a63fa +"is-number-object@npm:^1.0.4": + version: 1.0.6 + resolution: "is-number-object@npm:1.0.6" + dependencies: + has-tostringtag: ^1.0.0 + checksum: c697704e8fc2027fc41cb81d29805de4e8b6dc9c3efee93741dbf126a8ecc8443fef85adbc581415ae7e55d325e51d0a942324ae35c829131748cce39cba55f3 languageName: node linkType: hard -"json-buffer@npm:3.0.1": - version: 3.0.1 - resolution: "json-buffer@npm:3.0.1" - checksum: 9026b03edc2847eefa2e37646c579300a1f3a4586cfb62bf857832b60c852042d0d6ae55d1afb8926163fa54c2b01d83ae24705f34990348bdac6273a29d4581 +"is-number@npm:^7.0.0": + version: 7.0.0 + resolution: "is-number@npm:7.0.0" + checksum: 456ac6f8e0f3111ed34668a624e45315201dff921e5ac181f8ec24923b99e9f32ca1a194912dc79d539c97d33dba17dc635202ff0b2cf98326f608323276d27a languageName: node linkType: hard -"json-parse-better-errors@npm:^1.0.1": - version: 1.0.2 - resolution: "json-parse-better-errors@npm:1.0.2" - checksum: ff2b5ba2a70e88fd97a3cb28c1840144c5ce8fae9cbeeddba15afa333a5c407cf0e42300cd0a2885dbb055227fe68d405070faad941beeffbfde9cf3b2c78c5d +"is-path-inside@npm:^3.0.3": + version: 3.0.3 + resolution: "is-path-inside@npm:3.0.3" + checksum: abd50f06186a052b349c15e55b182326f1936c89a78bf6c8f2b707412517c097ce04bc49a0ca221787bc44e1049f51f09a2ffb63d22899051988d3a618ba13e9 languageName: node linkType: hard -"json-parse-even-better-errors@npm:^2.3.0": - version: 2.3.1 - resolution: "json-parse-even-better-errors@npm:2.3.1" - checksum: 798ed4cf3354a2d9ccd78e86d2169515a0097a5c133337807cdf7f1fc32e1391d207ccfc276518cc1d7d8d4db93288b8a50ba4293d212ad1336e52a8ec0a941f +"is-plain-obj@npm:^2.1.0": + version: 2.1.0 + resolution: "is-plain-obj@npm:2.1.0" + checksum: cec9100678b0a9fe0248a81743041ed990c2d4c99f893d935545cfbc42876cbe86d207f3b895700c690ad2fa520e568c44afc1605044b535a7820c1d40e38daa languageName: node linkType: hard -"json-rpc-engine@npm:^3.4.0, json-rpc-engine@npm:^3.6.0": - version: 3.8.0 - resolution: "json-rpc-engine@npm:3.8.0" +"is-regex@npm:^1.1.4": + version: 1.1.4 + resolution: "is-regex@npm:1.1.4" dependencies: - async: ^2.0.1 - babel-preset-env: ^1.7.0 - babelify: ^7.3.0 - json-rpc-error: ^2.0.0 - promise-to-callback: ^1.0.0 - safe-event-emitter: ^1.0.1 - checksum: 4a02ddda196b68717cdcdf9bc8eac91f956b717431daf1f317e016d564bd5b8974e8a66f75fd1f069d63b8e944128020ec7c371f28cf29ac0951d3338b2f667c + call-bind: ^1.0.2 + has-tostringtag: ^1.0.0 + checksum: 362399b33535bc8f386d96c45c9feb04cf7f8b41c182f54174c1a45c9abbbe5e31290bbad09a458583ff6bf3b2048672cdb1881b13289569a7c548370856a652 languageName: node linkType: hard -"json-rpc-error@npm:^2.0.0": - version: 2.0.0 - resolution: "json-rpc-error@npm:2.0.0" - dependencies: - inherits: ^2.0.1 - checksum: bbfb1ff82d0605b4dfd4ac6d093e863a8f623e0e83a098ccab5711a08d2ae09ea603260d4573a524e596701e64733690a5c31901e99daebe05b09053d8702d0c +"is-shared-array-buffer@npm:^1.0.1": + version: 1.0.1 + resolution: "is-shared-array-buffer@npm:1.0.1" + checksum: 2ffb92533e64e2876e6cfe6906871d28400b6f1a53130fe652ec8007bc0e5044d05e7af8e31bdc992fbba520bd92938cfbeedd0f286be92f250c7c76191c4d90 languageName: node linkType: hard -"json-rpc-random-id@npm:^1.0.0": - version: 1.0.1 - resolution: "json-rpc-random-id@npm:1.0.1" - checksum: fcd2e884193a129ace4002bd65a86e9cdb206733b4693baea77bd8b372cf8de3043fbea27716a2c9a716581a908ca8d978d9dfec4847eb2cf77edb4cf4b2252c +"is-shared-array-buffer@npm:^1.0.2": + version: 1.0.2 + resolution: "is-shared-array-buffer@npm:1.0.2" + dependencies: + call-bind: ^1.0.2 + checksum: 9508929cf14fdc1afc9d61d723c6e8d34f5e117f0bffda4d97e7a5d88c3a8681f633a74f8e3ad1fe92d5113f9b921dc5ca44356492079612f9a247efbce7032a languageName: node linkType: hard -"json-schema-traverse@npm:^0.4.1": - version: 0.4.1 - resolution: "json-schema-traverse@npm:0.4.1" - checksum: 7486074d3ba247769fda17d5181b345c9fb7d12e0da98b22d1d71a5db9698d8b4bd900a3ec1a4ffdd60846fc2556274a5c894d0c48795f14cb03aeae7b55260b +"is-stream@npm:^2.0.0": + version: 2.0.1 + resolution: "is-stream@npm:2.0.1" + checksum: b8e05ccdf96ac330ea83c12450304d4a591f9958c11fd17bed240af8d5ffe08aedafa4c0f4cfccd4d28dc9d4d129daca1023633d5c11601a6cbc77521f6fae66 languageName: node linkType: hard -"json-schema-traverse@npm:^1.0.0": - version: 1.0.0 - resolution: "json-schema-traverse@npm:1.0.0" - checksum: 02f2f466cdb0362558b2f1fd5e15cce82ef55d60cd7f8fa828cf35ba74330f8d767fcae5c5c2adb7851fa811766c694b9405810879bc4e1ddd78a7c0e03658ad +"is-string@npm:^1.0.5, is-string@npm:^1.0.7": + version: 1.0.7 + resolution: "is-string@npm:1.0.7" + dependencies: + has-tostringtag: ^1.0.0 + checksum: 323b3d04622f78d45077cf89aab783b2f49d24dc641aa89b5ad1a72114cfeff2585efc8c12ef42466dff32bde93d839ad321b26884cf75e5a7892a938b089989 languageName: node linkType: hard -"json-schema@npm:0.2.3": - version: 0.2.3 - resolution: "json-schema@npm:0.2.3" - checksum: bbc2070988fb5f2a2266a31b956f1b5660e03ea7eaa95b33402901274f625feb586ae0c485e1df854fde40a7f0dc679f3b3ca8e5b8d31f8ea07a0d834de785c7 +"is-symbol@npm:^1.0.2, is-symbol@npm:^1.0.3": + version: 1.0.4 + resolution: "is-symbol@npm:1.0.4" + dependencies: + has-symbols: ^1.0.2 + checksum: 92805812ef590738d9de49d677cd17dfd486794773fb6fa0032d16452af46e9b91bb43ffe82c983570f015b37136f4b53b28b8523bfb10b0ece7a66c31a54510 languageName: node linkType: hard -"json-stable-stringify-without-jsonify@npm:^1.0.1": - version: 1.0.1 - resolution: "json-stable-stringify-without-jsonify@npm:1.0.1" - checksum: cff44156ddce9c67c44386ad5cddf91925fe06b1d217f2da9c4910d01f358c6e3989c4d5a02683c7a5667f9727ff05831f7aa8ae66c8ff691c556f0884d49215 +"is-typed-array@npm:^1.1.10, is-typed-array@npm:^1.1.12": + version: 1.1.12 + resolution: "is-typed-array@npm:1.1.12" + dependencies: + which-typed-array: ^1.1.11 + checksum: 4c89c4a3be07186caddadf92197b17fda663a9d259ea0d44a85f171558270d36059d1c386d34a12cba22dfade5aba497ce22778e866adc9406098c8fc4771796 languageName: node linkType: hard -"json-stable-stringify@npm:^1.0.1": - version: 1.0.1 - resolution: "json-stable-stringify@npm:1.0.1" +"is-typed-array@npm:^1.1.3, is-typed-array@npm:^1.1.9": + version: 1.1.9 + resolution: "is-typed-array@npm:1.1.9" dependencies: - jsonify: ~0.0.0 - checksum: 65d6cbf0fca72a4136999f65f4401cf39a129f7aeff0fdd987ac3d3423a2113659294045fb8377e6e20d865cac32b1b8d70f3d87346c9786adcee60661d96ca5 + available-typed-arrays: ^1.0.5 + call-bind: ^1.0.2 + es-abstract: ^1.20.0 + for-each: ^0.3.3 + has-tostringtag: ^1.0.0 + checksum: 11910f1e58755fef43bf0074e52fa5b932bf101ec65d613e0a83d40e8e4c6e3f2ee142d624ebc7624c091d3bbe921131f8db7d36ecbbb71909f2fe310c1faa65 languageName: node linkType: hard -"json-stringify-safe@npm:^5.0.1, json-stringify-safe@npm:~5.0.1": - version: 5.0.1 - resolution: "json-stringify-safe@npm:5.0.1" - checksum: 48ec0adad5280b8a96bb93f4563aa1667fd7a36334f79149abd42446d0989f2ddc58274b479f4819f1f00617957e6344c886c55d05a4e15ebb4ab931e4a6a8ee +"is-typedarray@npm:^1.0.0, is-typedarray@npm:~1.0.0": + version: 1.0.0 + resolution: "is-typedarray@npm:1.0.0" + checksum: 3508c6cd0a9ee2e0df2fa2e9baabcdc89e911c7bd5cf64604586697212feec525aa21050e48affb5ffc3df20f0f5d2e2cf79b08caa64e1ccc9578e251763aef7 languageName: node linkType: hard -"json5@npm:^0.5.1": - version: 0.5.1 - resolution: "json5@npm:0.5.1" - bin: - json5: lib/cli.js - checksum: 9b85bf06955b23eaa4b7328aa8892e3887e81ca731dd27af04a5f5f1458fbc5e1de57a24442e3272f8a888dd1abe1cb68eb693324035f6b3aeba4fcab7667d62 +"is-unicode-supported@npm:^0.1.0": + version: 0.1.0 + resolution: "is-unicode-supported@npm:0.1.0" + checksum: a2aab86ee7712f5c2f999180daaba5f361bdad1efadc9610ff5b8ab5495b86e4f627839d085c6530363c6d6d4ecbde340fb8e54bdb83da4ba8e0865ed5513c52 languageName: node linkType: hard -"json5@npm:^1.0.1": +"is-weakref@npm:^1.0.1": version: 1.0.1 - resolution: "json5@npm:1.0.1" + resolution: "is-weakref@npm:1.0.1" dependencies: - minimist: ^1.2.0 - bin: - json5: lib/cli.js - checksum: e76ea23dbb8fc1348c143da628134a98adf4c5a4e8ea2adaa74a80c455fc2cdf0e2e13e6398ef819bfe92306b610ebb2002668ed9fc1af386d593691ef346fc3 + call-bind: ^1.0.0 + checksum: fdafb7b955671dd2f9658ff47c86e4025c0650fc68a3542a40e5a75898a763b1abd6b1e1f9f13207eed49541cdd76af67d73c44989ea358b201b70274cf8f6c1 languageName: node linkType: hard -"json@npm:^11.0.0": - version: 11.0.0 - resolution: "json@npm:11.0.0" - bin: - json: lib/json.js - checksum: 0beb8689722fc30251638543caf791bedc1a25199c18eb0281de115a0dadb00a07d4d36cbd7ff7680e04157fcb2bba76f29ed940b1e4e92f60c6fbaa74523fce +"is-weakref@npm:^1.0.2": + version: 1.0.2 + resolution: "is-weakref@npm:1.0.2" + dependencies: + call-bind: ^1.0.2 + checksum: 95bd9a57cdcb58c63b1c401c60a474b0f45b94719c30f548c891860f051bc2231575c290a6b420c6bc6e7ed99459d424c652bd5bf9a1d5259505dc35b4bf83de languageName: node linkType: hard -"jsonfile@npm:^2.1.0": - version: 2.4.0 - resolution: "jsonfile@npm:2.4.0" +"is-wsl@npm:^2.2.0": + version: 2.2.0 + resolution: "is-wsl@npm:2.2.0" dependencies: - graceful-fs: ^4.1.6 - dependenciesMeta: - graceful-fs: - optional: true - checksum: f5064aabbc9e35530dc471d8b203ae1f40dbe949ddde4391c6f6a6d310619a15f0efdae5587df594d1d70c555193aaeee9d2ed4aec9ffd5767bd5e4e62d49c3d + is-docker: ^2.0.0 + checksum: 20849846ae414997d290b75e16868e5261e86ff5047f104027026fd61d8b5a9b0b3ade16239f35e1a067b3c7cc02f70183cb661010ed16f4b6c7c93dad1b19d8 languageName: node linkType: hard -"jsonfile@npm:^4.0.0": - version: 4.0.0 - resolution: "jsonfile@npm:4.0.0" - dependencies: - graceful-fs: ^4.1.6 - dependenciesMeta: - graceful-fs: - optional: true - checksum: 6447d6224f0d31623eef9b51185af03ac328a7553efcee30fa423d98a9e276ca08db87d71e17f2310b0263fd3ffa6c2a90a6308367f661dc21580f9469897c9e +"isarray@npm:0.0.1": + version: 0.0.1 + resolution: "isarray@npm:0.0.1" + checksum: 49191f1425681df4a18c2f0f93db3adb85573bcdd6a4482539d98eac9e705d8961317b01175627e860516a2fc45f8f9302db26e5a380a97a520e272e2a40a8d4 languageName: node linkType: hard -"jsonfile@npm:^6.0.1": - version: 6.1.0 - resolution: "jsonfile@npm:6.1.0" - dependencies: - graceful-fs: ^4.1.6 - universalify: ^2.0.0 - dependenciesMeta: - graceful-fs: - optional: true - checksum: 7af3b8e1ac8fe7f1eccc6263c6ca14e1966fcbc74b618d3c78a0a2075579487547b94f72b7a1114e844a1e15bb00d440e5d1720bfc4612d790a6f285d5ea8354 +"isarray@npm:^1.0.0, isarray@npm:~1.0.0": + version: 1.0.0 + resolution: "isarray@npm:1.0.0" + checksum: f032df8e02dce8ec565cf2eb605ea939bdccea528dbcf565cdf92bfa2da9110461159d86a537388ef1acef8815a330642d7885b29010e8f7eac967c9993b65ab languageName: node linkType: hard -"jsonify@npm:~0.0.0": - version: 0.0.1 - resolution: "jsonify@npm:0.0.1" - checksum: 027287e1c0294fce15f18c0ff990cfc2318e7f01fb76515f784d5cd0784abfec6fc5c2355c3a2f2cb0ad7f4aa2f5b74ebbfe4e80476c35b2d13cabdb572e1134 +"isarray@npm:^2.0.5": + version: 2.0.5 + resolution: "isarray@npm:2.0.5" + checksum: bd5bbe4104438c4196ba58a54650116007fa0262eccef13a4c55b2e09a5b36b59f1e75b9fcc49883dd9d4953892e6fc007eef9e9155648ceea036e184b0f930a languageName: node linkType: hard -"jsonparse@npm:^1.2.0": - version: 1.3.1 - resolution: "jsonparse@npm:1.3.1" - checksum: 6514a7be4674ebf407afca0eda3ba284b69b07f9958a8d3113ef1005f7ec610860c312be067e450c569aab8b89635e332cee3696789c750692bb60daba627f4d +"isexe@npm:^2.0.0": + version: 2.0.0 + resolution: "isexe@npm:2.0.0" + checksum: 26bf6c5480dda5161c820c5b5c751ae1e766c587b1f951ea3fcfc973bafb7831ae5b54a31a69bd670220e42e99ec154475025a468eae58ea262f813fdc8d1c62 languageName: node linkType: hard -"jsonschema@npm:^1.2.4": - version: 1.4.1 - resolution: "jsonschema@npm:1.4.1" - checksum: 1ef02a6cd9bc32241ec86bbf1300bdbc3b5f2d8df6eb795517cf7d1cd9909e7beba1e54fdf73990fd66be98a182bda9add9607296b0cb00b1348212988e424b2 +"iso-url@npm:^1.1.5": + version: 1.2.1 + resolution: "iso-url@npm:1.2.1" + checksum: 1af98c4ed6a39598407fd8c3c13e997c978985f477af2be3390d2aa3e422b4b5992ffbb0dac68656b165c71850fff748ac1309d29d4f2a728707d76bf0f98557 languageName: node linkType: hard -"jsprim@npm:^1.2.2": - version: 1.4.1 - resolution: "jsprim@npm:1.4.1" +"isomorphic-unfetch@npm:^3.0.0": + version: 3.1.0 + resolution: "isomorphic-unfetch@npm:3.1.0" dependencies: - assert-plus: 1.0.0 - extsprintf: 1.3.0 - json-schema: 0.2.3 - verror: 1.10.0 - checksum: 6bcb20ec265ae18bb48e540a6da2c65f9c844f7522712d6dfcb01039527a49414816f4869000493363f1e1ea96cbad00e46188d5ecc78257a19f152467587373 + node-fetch: ^2.6.1 + unfetch: ^4.2.0 + checksum: 82b92fe4ec2823a81ab0fc0d11bd94d710e6f9a940d56b3cba31896d4345ec9ffc7949f4ff31ebcae84f6b95f7ebf3474c4c7452b834eb4078ea3f2c37e459c5 + languageName: node + linkType: hard + +"isomorphic-ws@npm:^4.0.1": + version: 4.0.1 + resolution: "isomorphic-ws@npm:4.0.1" + peerDependencies: + ws: "*" + checksum: d7190eadefdc28bdb93d67b5f0c603385aaf87724fa2974abb382ac1ec9756ed2cfb27065cbe76122879c2d452e2982bc4314317f3d6c737ddda6c047328771a languageName: node linkType: hard -"keccak@npm:3.0.1": - version: 3.0.1 - resolution: "keccak@npm:3.0.1" - dependencies: - node-addon-api: ^2.0.0 - node-gyp: latest - node-gyp-build: ^4.2.0 - checksum: 1de1b62fbb3e035ee186232b11f154bd5c2c12a2d910bc8ec313dab412b6f39ddc51d3a105618dd8de752875da0ead21abb0eb1d4e7d7b17771a4acbb7159390 +"isows@npm:1.0.7": + version: 1.0.7 + resolution: "isows@npm:1.0.7" + peerDependencies: + ws: "*" + checksum: 044b949b369872882af07b60b613b5801ae01b01a23b5b72b78af80c8103bbeed38352c3e8ceff13a7834bc91fd2eb41cf91ec01d59a041d8705680e6b0ec546 languageName: node linkType: hard -"keccak@npm:^3.0.0, keccak@npm:^3.0.2": - version: 3.0.2 - resolution: "keccak@npm:3.0.2" - dependencies: - node-addon-api: ^2.0.0 - node-gyp: latest - node-gyp-build: ^4.2.0 - readable-stream: ^3.6.0 - checksum: 39a7d6128b8ee4cb7dcd186fc7e20c6087cc39f573a0f81b147c323f688f1f7c2b34f62c4ae189fe9b81c6730b2d1228d8a399cdc1f3d8a4c8f030cdc4f20272 +"isstream@npm:~0.1.2": + version: 0.1.2 + resolution: "isstream@npm:0.1.2" + checksum: 1eb2fe63a729f7bdd8a559ab552c69055f4f48eb5c2f03724430587c6f450783c8f1cd936c1c952d0a927925180fcc892ebd5b174236cf1065d4bd5bdb37e963 languageName: node linkType: hard -"keccak@npm:^3.0.3": - version: 3.0.3 - resolution: "keccak@npm:3.0.3" - dependencies: - node-addon-api: ^2.0.0 - node-gyp: latest - node-gyp-build: ^4.2.0 - readable-stream: ^3.6.0 - checksum: f08f04f5cc87013a3fc9e87262f761daff38945c86dd09c01a7f7930a15ae3e14f93b310ef821dcc83675a7b814eb1c983222399a2f263ad980251201d1b9a99 +"it-all@npm:^1.0.4": + version: 1.0.6 + resolution: "it-all@npm:1.0.6" + checksum: 7ca9a528c08ebe2fc8a3c93a41409219d18325ed31fedb9834ebac2822f0b2a96d7abcb6cbfa092114ab4d5f08951e694c7a2c3929ce4b5300769e710ae665db languageName: node linkType: hard -"keyv@npm:^3.0.0": - version: 3.1.0 - resolution: "keyv@npm:3.1.0" - dependencies: - json-buffer: 3.0.0 - checksum: bb7e8f3acffdbafbc2dd5b63f377fe6ec4c0e2c44fc82720449ef8ab54f4a7ce3802671ed94c0f475ae0a8549703353a2124561fcf3317010c141b32ca1ce903 +"it-first@npm:^1.0.6": + version: 1.0.7 + resolution: "it-first@npm:1.0.7" + checksum: 0c9106d29120f02e68a08118de328437fb44c966385635d672684d4f0321ee22ca470a30f390132bdb454da0d4d3abb82c796dad8e391a827f1a3446711c7685 languageName: node linkType: hard -"keyv@npm:^4.0.0": - version: 4.5.0 - resolution: "keyv@npm:4.5.0" +"it-glob@npm:^1.0.1": + version: 1.0.2 + resolution: "it-glob@npm:1.0.2" dependencies: - json-buffer: 3.0.1 - checksum: d294873cf88ec8f691e5edeb7b4b884f886c5f021a01902a0e243c362449db2b55419d7fb7187d059add747b7398321e39e44d391b65f94935174ce13452714d + "@types/minimatch": ^3.0.4 + minimatch: ^3.0.4 + checksum: 629e7b66510006041df98882acfd73ac785836d51fc3ffa5c83c7099f931b3287a64c5a3772e7c1e46b63f1d511a9222f5b637c50f1c738222b46d104ff2e91c languageName: node linkType: hard -"kind-of@npm:^3.0.2, kind-of@npm:^3.0.3, kind-of@npm:^3.2.0": - version: 3.2.2 - resolution: "kind-of@npm:3.2.2" - dependencies: - is-buffer: ^1.1.5 - checksum: e898df8ca2f31038f27d24f0b8080da7be274f986bc6ed176f37c77c454d76627619e1681f6f9d2e8d2fd7557a18ecc419a6bb54e422abcbb8da8f1a75e4b386 +"it-last@npm:^1.0.4": + version: 1.0.6 + resolution: "it-last@npm:1.0.6" + checksum: bc7b68ddd6cae902f0095d0c7ccb0078abdfa41fbf55862a9df9e30ae74be08282b5b3d21f40e6103af0d202144974e216d3c44f3e8f93c2c3f890322b02fcfa languageName: node linkType: hard -"kind-of@npm:^4.0.0": - version: 4.0.0 - resolution: "kind-of@npm:4.0.0" - dependencies: - is-buffer: ^1.1.5 - checksum: 1b9e7624a8771b5a2489026e820f3bbbcc67893e1345804a56b23a91e9069965854d2a223a7c6ee563c45be9d8c6ff1ef87f28ed5f0d1a8d00d9dcbb067c529f +"it-map@npm:^1.0.4": + version: 1.0.6 + resolution: "it-map@npm:1.0.6" + checksum: 5eb9da69e5d58624c79cea13dd8eeffe8a1ab6a28a527ac4d0301304279ffbe8da94faf50aa269e2a1630c94dc30a6bfe7a135bfb0c7e887216efad7c41a9f52 languageName: node linkType: hard -"kind-of@npm:^5.0.0": - version: 5.1.0 - resolution: "kind-of@npm:5.1.0" - checksum: f2a0102ae0cf19c4a953397e552571bad2b588b53282874f25fca7236396e650e2db50d41f9f516bd402536e4df968dbb51b8e69e4d5d4a7173def78448f7bab +"it-peekable@npm:^1.0.2": + version: 1.0.3 + resolution: "it-peekable@npm:1.0.3" + checksum: 6e9d68cbf582e301f191b8ad2660957c12c8100804a298fd5732ee35f2dd466a6af64d88d91343f2614675b4d4fb546618335303e9356659a9a0868c08b1ca54 languageName: node linkType: hard -"kind-of@npm:^6.0.0, kind-of@npm:^6.0.2": - version: 6.0.3 - resolution: "kind-of@npm:6.0.3" - checksum: 3ab01e7b1d440b22fe4c31f23d8d38b4d9b91d9f291df683476576493d5dfd2e03848a8b05813dd0c3f0e835bc63f433007ddeceb71f05cb25c45ae1b19c6d3b +"it-to-stream@npm:^1.0.0": + version: 1.0.0 + resolution: "it-to-stream@npm:1.0.0" + dependencies: + buffer: ^6.0.3 + fast-fifo: ^1.0.0 + get-iterator: ^1.0.2 + p-defer: ^3.0.0 + p-fifo: ^1.0.0 + readable-stream: ^3.6.0 + checksum: e0c5a3f3c90d4bc52686217865b8fa202f64bd3af493dec0fdacd58b4237166fb68935ff2823ed0a16414ba5becb9a5fb8c98f3ec99584789776d7277c1d129f languageName: node linkType: hard -"klaw-sync@npm:^6.0.0": - version: 6.0.0 - resolution: "klaw-sync@npm:6.0.0" +"jake@npm:^10.6.1, jake@npm:^10.8.5": + version: 10.8.7 + resolution: "jake@npm:10.8.7" dependencies: - graceful-fs: ^4.1.11 - checksum: 0da397f8961313c3ef8f79fb63af9002cde5a8fb2aeb1a37351feff0dd6006129c790400c3f5c3b4e757bedcabb13d21ec0a5eaef5a593d59515d4f2c291e475 + async: ^3.2.3 + chalk: ^4.0.2 + filelist: ^1.0.4 + minimatch: ^3.1.2 + bin: + jake: bin/cli.js + checksum: a23fd2273fb13f0d0d845502d02c791fd55ef5c6a2d207df72f72d8e1eac6d2b8ffa6caf660bc8006b3242e0daaa88a3ecc600194d72b5c6016ad56e9cd43553 languageName: node linkType: hard -"klaw@npm:^1.0.0": - version: 1.3.1 - resolution: "klaw@npm:1.3.1" +"jayson@npm:4.0.0": + version: 4.0.0 + resolution: "jayson@npm:4.0.0" dependencies: - graceful-fs: ^4.1.9 - dependenciesMeta: - graceful-fs: - optional: true - checksum: 8f69e4797c26e7c3f2426bfa85f38a3da3c2cb1b4c6bd850d2377aed440d41ce9d806f2885c2e2e224372c56af4b1d43b8a499adecf9a05e7373dc6b8b7c52e4 + "@types/connect": ^3.4.33 + "@types/node": ^12.12.54 + "@types/ws": ^7.4.4 + JSONStream: ^1.3.5 + commander: ^2.20.3 + delay: ^5.0.0 + es6-promisify: ^5.0.0 + eyes: ^0.1.8 + isomorphic-ws: ^4.0.1 + json-stringify-safe: ^5.0.1 + uuid: ^8.3.2 + ws: ^7.4.5 + bin: + jayson: bin/jayson.js + checksum: 39eed3dc8d0e35320b0234f0faf7d6195b0cdc6940ec969f603a3ea14de8da98f2bd2775e3b982fe1ee6de63e66428fbf322d426e659fa25ea86c8ac92c8710d languageName: node linkType: hard -"kleur@npm:^3.0.3": - version: 3.0.3 - resolution: "kleur@npm:3.0.3" - checksum: df82cd1e172f957bae9c536286265a5cdbd5eeca487cb0a3b2a7b41ef959fc61f8e7c0e9aeea9c114ccf2c166b6a8dd45a46fd619c1c569d210ecd2765ad5169 +"js-cookie@npm:^2.2.1": + version: 2.2.1 + resolution: "js-cookie@npm:2.2.1" + checksum: 9b1fb980a1c5e624fd4b28ea4867bb30c71e04c4484bb3a42766344c533faa684de9498e443425479ec68609e96e27b60614bfe354877c449c631529b6d932f2 languageName: node linkType: hard -"lcid@npm:^1.0.0": - version: 1.0.0 - resolution: "lcid@npm:1.0.0" - dependencies: - invert-kv: ^1.0.0 - checksum: e8c7a4db07663068c5c44b650938a2bc41aa992037eebb69376214320f202c1250e70b50c32f939e28345fd30c2d35b8e8cd9a19d5932c398246a864ce54843d +"js-sha3@npm:0.5.7, js-sha3@npm:^0.5.7": + version: 0.5.7 + resolution: "js-sha3@npm:0.5.7" + checksum: 973a28ea4b26cc7f12d2ab24f796e24ee4a71eef45a6634a052f6eb38cf8b2333db798e896e6e094ea6fa4dfe8e42a2a7942b425cf40da3f866623fd05bb91ea languageName: node linkType: hard -"lcid@npm:^2.0.0": - version: 2.0.0 - resolution: "lcid@npm:2.0.0" - dependencies: - invert-kv: ^2.0.0 - checksum: 278e27b5a0707cf9ab682146963ebff2328795be10cd6f8ea8edae293439325d345ac5e33079cce77ac3a86a3dcfb97a34f279dbc46b03f3e419aa39b5915a16 +"js-sha3@npm:0.8.0, js-sha3@npm:^0.8.0": + version: 0.8.0 + resolution: "js-sha3@npm:0.8.0" + checksum: 75df77c1fc266973f06cce8309ce010e9e9f07ec35ab12022ed29b7f0d9c8757f5a73e1b35aa24840dced0dea7059085aa143d817aea9e188e2a80d569d9adce languageName: node linkType: hard -"level-codec@npm:^9.0.0": - version: 9.0.2 - resolution: "level-codec@npm:9.0.2" - dependencies: - buffer: ^5.6.0 - checksum: 289003d51b8afcdd24c4d318606abf2bae81975e4b527d7349abfdbacc8fef26711f2f24e2d20da0e1dce0bb216a856c9433ccb9ca25fa78a96aed9f51e506ed +"js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0": + version: 4.0.0 + resolution: "js-tokens@npm:4.0.0" + checksum: 8a95213a5a77deb6cbe94d86340e8d9ace2b93bc367790b260101d2f36a2eaf4e4e22d9fa9cf459b38af3a32fb4190e638024cf82ec95ef708680e405ea7cc78 languageName: node linkType: hard -"level-codec@npm:~7.0.0": - version: 7.0.1 - resolution: "level-codec@npm:7.0.1" - checksum: 2565c131d93aea0786af5eda9bb907e3f5152fade03fd7a7751e2f95301fc5241063eb927c2f7df086fac33592523aab8df86bcf7ecc46ed53de11453b600329 +"js-yaml@npm:3.13.1": + version: 3.13.1 + resolution: "js-yaml@npm:3.13.1" + dependencies: + argparse: ^1.0.7 + esprima: ^4.0.0 + bin: + js-yaml: bin/js-yaml.js + checksum: 7511b764abb66d8aa963379f7d2a404f078457d106552d05a7b556d204f7932384e8477513c124749fa2de52eb328961834562bd09924902c6432e40daa408bc languageName: node linkType: hard -"level-concat-iterator@npm:~2.0.0": - version: 2.0.1 - resolution: "level-concat-iterator@npm:2.0.1" - checksum: 562583ef1292215f8e749c402510cb61c4d6fccf4541082b3d21dfa5ecde9fcccfe52bdcb5cfff9d2384e7ce5891f44df9439a6ddb39b0ffe31015600b4a828a +"js-yaml@npm:3.14.1, js-yaml@npm:3.x, js-yaml@npm:^3.12.0, js-yaml@npm:^3.13.0, js-yaml@npm:^3.13.1, js-yaml@npm:^3.14.1": + version: 3.14.1 + resolution: "js-yaml@npm:3.14.1" + dependencies: + argparse: ^1.0.7 + esprima: ^4.0.0 + bin: + js-yaml: bin/js-yaml.js + checksum: bef146085f472d44dee30ec34e5cf36bf89164f5d585435a3d3da89e52622dff0b188a580e4ad091c3341889e14cb88cac6e4deb16dc5b1e9623bb0601fc255c languageName: node linkType: hard -"level-errors@npm:^1.0.3": - version: 1.1.2 - resolution: "level-errors@npm:1.1.2" +"js-yaml@npm:4.1.0, js-yaml@npm:^4.1.0": + version: 4.1.0 + resolution: "js-yaml@npm:4.1.0" dependencies: - errno: ~0.1.1 - checksum: 18c22fd574ff31567642a85d9a306604a32cbe969b8469fee29620c10488214a6b5e6bbf19e3b5e2042859e4b81041af537319c18132a1aaa56d4ed5981157b7 + argparse: ^2.0.1 + bin: + js-yaml: bin/js-yaml.js + checksum: c7830dfd456c3ef2c6e355cc5a92e6700ceafa1d14bba54497b34a99f0376cecbb3e9ac14d3e5849b426d5a5140709a66237a8c991c675431271c4ce5504151a languageName: node linkType: hard -"level-errors@npm:^2.0.0, level-errors@npm:~2.0.0": - version: 2.0.1 - resolution: "level-errors@npm:2.0.1" - dependencies: - errno: ~0.1.1 - checksum: aca5d7670e2a40609db8d7743fce289bb5202c0bc13e4a78f81f36a6642e9abc0110f48087d3d3c2c04f023d70d4ee6f2db0e20c63d29b3fda323a67bfff6526 +"jsbn@npm:~0.1.0": + version: 0.1.1 + resolution: "jsbn@npm:0.1.1" + checksum: e5ff29c1b8d965017ef3f9c219dacd6e40ad355c664e277d31246c90545a02e6047018c16c60a00f36d561b3647215c41894f5d869ada6908a2e0ce4200c88f2 languageName: node linkType: hard -"level-errors@npm:~1.0.3": - version: 1.0.5 - resolution: "level-errors@npm:1.0.5" - dependencies: - errno: ~0.1.1 - checksum: a62df2a24987c0100855ec03f03655ddc6170b33a83987a53858ba0a7dbe125b4b5382e01068a1dc899ccf7f9d12b824702da15488bd06b4b3ee7a1e4232cb0a +"json-buffer@npm:3.0.1": + version: 3.0.1 + resolution: "json-buffer@npm:3.0.1" + checksum: 9026b03edc2847eefa2e37646c579300a1f3a4586cfb62bf857832b60c852042d0d6ae55d1afb8926163fa54c2b01d83ae24705f34990348bdac6273a29d4581 languageName: node linkType: hard -"level-iterator-stream@npm:^2.0.3": - version: 2.0.3 - resolution: "level-iterator-stream@npm:2.0.3" - dependencies: - inherits: ^2.0.1 - readable-stream: ^2.0.5 - xtend: ^4.0.0 - checksum: dd4211798d032a06ebc3e9c5a3a969b003cb15f1fe6398d9c50c87dc8b0bf8b07197cada253fd7f8c4a933f3c86e12bb041df1561c89b749ac4b991d6e68b17f +"json-parse-better-errors@npm:^1.0.1": + version: 1.0.2 + resolution: "json-parse-better-errors@npm:1.0.2" + checksum: ff2b5ba2a70e88fd97a3cb28c1840144c5ce8fae9cbeeddba15afa333a5c407cf0e42300cd0a2885dbb055227fe68d405070faad941beeffbfde9cf3b2c78c5d languageName: node linkType: hard -"level-iterator-stream@npm:~1.3.0": - version: 1.3.1 - resolution: "level-iterator-stream@npm:1.3.1" - dependencies: - inherits: ^2.0.1 - level-errors: ^1.0.3 - readable-stream: ^1.0.33 - xtend: ^4.0.0 - checksum: bf57d8dcee6e7ec68e6c580edc768d2e3960f93e741d7d4adcc7d86f267c741ebcfba5353b3b6551ca10d12e30939c90f1a13303313b1b719325111f0ff14540 +"json-parse-even-better-errors@npm:^2.3.0": + version: 2.3.1 + resolution: "json-parse-even-better-errors@npm:2.3.1" + checksum: 798ed4cf3354a2d9ccd78e86d2169515a0097a5c133337807cdf7f1fc32e1391d207ccfc276518cc1d7d8d4db93288b8a50ba4293d212ad1336e52a8ec0a941f languageName: node linkType: hard -"level-iterator-stream@npm:~3.0.0": - version: 3.0.1 - resolution: "level-iterator-stream@npm:3.0.1" - dependencies: - inherits: ^2.0.1 - readable-stream: ^2.3.6 - xtend: ^4.0.0 - checksum: f3348316907c70163ea15319ef7e28c21c6b4b948616e11dcbbb8e3dab9ec5b39f7bf13e0d53f7d23c69641b7a2985a4911c5c9a03bd57a07f1af469aba6e3a8 +"json-schema-traverse@npm:^0.4.1": + version: 0.4.1 + resolution: "json-schema-traverse@npm:0.4.1" + checksum: 7486074d3ba247769fda17d5181b345c9fb7d12e0da98b22d1d71a5db9698d8b4bd900a3ec1a4ffdd60846fc2556274a5c894d0c48795f14cb03aeae7b55260b languageName: node linkType: hard -"level-iterator-stream@npm:~4.0.0": - version: 4.0.2 - resolution: "level-iterator-stream@npm:4.0.2" - dependencies: - inherits: ^2.0.4 - readable-stream: ^3.4.0 - xtend: ^4.0.2 - checksum: 239e2c7e62bffb485ed696bcd3b98de7a2bc455d13be4fce175ae3544fe9cda81c2ed93d3e88b61380ae6d28cce02511862d77b86fb2ba5b5cf00471f3c1eccc +"json-schema-traverse@npm:^1.0.0": + version: 1.0.0 + resolution: "json-schema-traverse@npm:1.0.0" + checksum: 02f2f466cdb0362558b2f1fd5e15cce82ef55d60cd7f8fa828cf35ba74330f8d767fcae5c5c2adb7851fa811766c694b9405810879bc4e1ddd78a7c0e03658ad languageName: node linkType: hard -"level-mem@npm:^3.0.1": - version: 3.0.1 - resolution: "level-mem@npm:3.0.1" - dependencies: - level-packager: ~4.0.0 - memdown: ~3.0.0 - checksum: e4c680922afc3c8cd4502d761ab610c8aa7bcacde2550a0a463e1db069eeb55b6b7bec0bb7fda564cec82422944776f9909fe101b0d7746ad8f4f7446ec2a5cd +"json-schema@npm:0.2.3": + version: 0.2.3 + resolution: "json-schema@npm:0.2.3" + checksum: bbc2070988fb5f2a2266a31b956f1b5660e03ea7eaa95b33402901274f625feb586ae0c485e1df854fde40a7f0dc679f3b3ca8e5b8d31f8ea07a0d834de785c7 languageName: node linkType: hard -"level-mem@npm:^5.0.1": - version: 5.0.1 - resolution: "level-mem@npm:5.0.1" - dependencies: - level-packager: ^5.0.3 - memdown: ^5.0.0 - checksum: 37a38163b0c7cc55f64385fdff78438669f953bc08dc751739e2f1edd401472a89001a73a95cc8b81f38f989e46279797c11eb82e702690ea9a171e02bf31e84 +"json-stable-stringify-without-jsonify@npm:^1.0.1": + version: 1.0.1 + resolution: "json-stable-stringify-without-jsonify@npm:1.0.1" + checksum: cff44156ddce9c67c44386ad5cddf91925fe06b1d217f2da9c4910d01f358c6e3989c4d5a02683c7a5667f9727ff05831f7aa8ae66c8ff691c556f0884d49215 languageName: node linkType: hard -"level-packager@npm:^5.0.3": - version: 5.1.1 - resolution: "level-packager@npm:5.1.1" - dependencies: - encoding-down: ^6.3.0 - levelup: ^4.3.2 - checksum: befe2aa54f2010a6ecf7ddce392c8dee225e1839205080a2704d75e560e28b01191b345494696196777b70d376e3eaae4c9e7c330cc70d3000839f5b18dd78f2 +"json-stream-stringify@npm:^3.1.4": + version: 3.1.6 + resolution: "json-stream-stringify@npm:3.1.6" + checksum: ce873e09fe18461960b7536f63e2f913a2cb242819513856ed1af58989d41846976e7177cb1fe3c835220023aa01e534d56b6d5c3290a5b23793a6f4cb93785e languageName: node linkType: hard -"level-packager@npm:~4.0.0": - version: 4.0.1 - resolution: "level-packager@npm:4.0.1" - dependencies: - encoding-down: ~5.0.0 - levelup: ^3.0.0 - checksum: af33054cfdf1f3cb409941c2e6a67190c0437f8b57a518fa1d40d3f9fd75edbb72c2c17595a52b10030fe2d64c8ef474ddb570f925d88402c94cfc95263865cb +"json-stringify-safe@npm:^5.0.1, json-stringify-safe@npm:~5.0.1": + version: 5.0.1 + resolution: "json-stringify-safe@npm:5.0.1" + checksum: 48ec0adad5280b8a96bb93f4563aa1667fd7a36334f79149abd42446d0989f2ddc58274b479f4819f1f00617957e6344c886c55d05a4e15ebb4ab931e4a6a8ee languageName: node linkType: hard -"level-post@npm:^1.0.7": - version: 1.0.7 - resolution: "level-post@npm:1.0.7" +"json5@npm:^1.0.1": + version: 1.0.1 + resolution: "json5@npm:1.0.1" dependencies: - ltgt: ^2.1.2 - checksum: 27239cfebe2004036d7ed0ace860d03f829f099de62baf727cce53bd99cb06bfc4a202fa7cb828847fa01c421bab13d9d3e79c9554f5cffff681541dda575218 + minimist: ^1.2.0 + bin: + json5: lib/cli.js + checksum: e76ea23dbb8fc1348c143da628134a98adf4c5a4e8ea2adaa74a80c455fc2cdf0e2e13e6398ef819bfe92306b610ebb2002668ed9fc1af386d593691ef346fc3 languageName: node linkType: hard -"level-sublevel@npm:6.6.4": - version: 6.6.4 - resolution: "level-sublevel@npm:6.6.4" - dependencies: - bytewise: ~1.1.0 - level-codec: ^9.0.0 - level-errors: ^2.0.0 - level-iterator-stream: ^2.0.3 - ltgt: ~2.1.1 - pull-defer: ^0.2.2 - pull-level: ^2.0.3 - pull-stream: ^3.6.8 - typewiselite: ~1.0.0 - xtend: ~4.0.0 - checksum: 8370e6fbf67bf08daa23de07699d3d2ccf6a349a28db4025a890d4c07857811808372fdf5029c4afedf24e2ff828be6bb7cd9fd0b676090daba38981b2e75cff +"json@npm:^11.0.0": + version: 11.0.0 + resolution: "json@npm:11.0.0" + bin: + json: lib/json.js + checksum: 0beb8689722fc30251638543caf791bedc1a25199c18eb0281de115a0dadb00a07d4d36cbd7ff7680e04157fcb2bba76f29ed940b1e4e92f60c6fbaa74523fce languageName: node linkType: hard -"level-supports@npm:^4.0.0": - version: 4.0.1 - resolution: "level-supports@npm:4.0.1" - checksum: d4552b42bb8cdeada07b0f6356c7a90fefe76279147331f291aceae26e3e56d5f927b09ce921647c0230bfe03ddfbdcef332be921e5c2194421ae2bfa3cf6368 +"jsonfile@npm:^4.0.0": + version: 4.0.0 + resolution: "jsonfile@npm:4.0.0" + dependencies: + graceful-fs: ^4.1.6 + dependenciesMeta: + graceful-fs: + optional: true + checksum: 6447d6224f0d31623eef9b51185af03ac328a7553efcee30fa423d98a9e276ca08db87d71e17f2310b0263fd3ffa6c2a90a6308367f661dc21580f9469897c9e languageName: node linkType: hard -"level-supports@npm:~1.0.0": - version: 1.0.1 - resolution: "level-supports@npm:1.0.1" +"jsonfile@npm:^6.0.1": + version: 6.1.0 + resolution: "jsonfile@npm:6.1.0" dependencies: - xtend: ^4.0.2 - checksum: 5d6bdb88cf00c3d9adcde970db06a548c72c5a94bf42c72f998b58341a105bfe2ea30d313ce1e84396b98cc9ddbc0a9bd94574955a86e929f73c986e10fc0df0 + graceful-fs: ^4.1.6 + universalify: ^2.0.0 + dependenciesMeta: + graceful-fs: + optional: true + checksum: 7af3b8e1ac8fe7f1eccc6263c6ca14e1966fcbc74b618d3c78a0a2075579487547b94f72b7a1114e844a1e15bb00d440e5d1720bfc4612d790a6f285d5ea8354 languageName: node linkType: hard -"level-transcoder@npm:^1.0.1": - version: 1.0.1 - resolution: "level-transcoder@npm:1.0.1" - dependencies: - buffer: ^6.0.3 - module-error: ^1.0.1 - checksum: 304f08d802faf3491a533b6d87ad8be3cabfd27f2713bbe9d4c633bf50fcb9460eab5a6776bf015e101ead7ba1c1853e05e7f341112f17a9d0cb37ee5a421a25 +"jsonparse@npm:^1.2.0": + version: 1.3.1 + resolution: "jsonparse@npm:1.3.1" + checksum: 6514a7be4674ebf407afca0eda3ba284b69b07f9958a8d3113ef1005f7ec610860c312be067e450c569aab8b89635e332cee3696789c750692bb60daba627f4d languageName: node linkType: hard -"level-ws@npm:0.0.0": - version: 0.0.0 - resolution: "level-ws@npm:0.0.0" - dependencies: - readable-stream: ~1.0.15 - xtend: ~2.1.1 - checksum: fcc3e6993b538ed8931612a74ef26cf32b53d71c059a819bb1006c075f0c1198afb79026a69aeeafcbd4598c45b4b214315b4216b44eca68587fce1b5ad61b75 +"jsonschema@npm:^1.2.4": + version: 1.4.1 + resolution: "jsonschema@npm:1.4.1" + checksum: 1ef02a6cd9bc32241ec86bbf1300bdbc3b5f2d8df6eb795517cf7d1cd9909e7beba1e54fdf73990fd66be98a182bda9add9607296b0cb00b1348212988e424b2 languageName: node linkType: hard -"level-ws@npm:^1.0.0": - version: 1.0.0 - resolution: "level-ws@npm:1.0.0" +"jsprim@npm:^1.2.2": + version: 1.4.1 + resolution: "jsprim@npm:1.4.1" dependencies: - inherits: ^2.0.3 - readable-stream: ^2.2.8 - xtend: ^4.0.1 - checksum: 752fd0f89eb1ccf811c09de24ca8987437ea84f88e672d0037324fb5d71c5bc022c25ba64d6a00fca33beec48a81e3cd1ef99c2f9fff267b3a4f2233939fad35 + assert-plus: 1.0.0 + extsprintf: 1.3.0 + json-schema: 0.2.3 + verror: 1.10.0 + checksum: 6bcb20ec265ae18bb48e540a6da2c65f9c844f7522712d6dfcb01039527a49414816f4869000493363f1e1ea96cbad00e46188d5ecc78257a19f152467587373 languageName: node linkType: hard -"level-ws@npm:^2.0.0": - version: 2.0.0 - resolution: "level-ws@npm:2.0.0" +"keccak@npm:^3.0.0, keccak@npm:^3.0.2": + version: 3.0.2 + resolution: "keccak@npm:3.0.2" dependencies: - inherits: ^2.0.3 - readable-stream: ^3.1.0 - xtend: ^4.0.1 - checksum: 4e5cbf090a07367373f693c98ad5b4797e7e694ea801ce5cd4103e06837ec883bdce9588ac11e0b9963ca144b96c95c6401c9e43583028ba1e4f847e81ec9ad6 + node-addon-api: ^2.0.0 + node-gyp: latest + node-gyp-build: ^4.2.0 + readable-stream: ^3.6.0 + checksum: 39a7d6128b8ee4cb7dcd186fc7e20c6087cc39f573a0f81b147c323f688f1f7c2b34f62c4ae189fe9b81c6730b2d1228d8a399cdc1f3d8a4c8f030cdc4f20272 languageName: node linkType: hard -"level@npm:^8.0.0": - version: 8.0.0 - resolution: "level@npm:8.0.0" +"keccak@npm:^3.0.3": + version: 3.0.3 + resolution: "keccak@npm:3.0.3" dependencies: - browser-level: ^1.0.1 - classic-level: ^1.2.0 - checksum: 13eb25bd71bfdca6cd714d1233adf9da97de9a8a4bf9f28d62a390b5c96d0250abaf983eb90eb8c4e89c7a985bb330750683d106f12670e5ea8fba1d7e608a1f + node-addon-api: ^2.0.0 + node-gyp: latest + node-gyp-build: ^4.2.0 + readable-stream: ^3.6.0 + checksum: f08f04f5cc87013a3fc9e87262f761daff38945c86dd09c01a7f7930a15ae3e14f93b310ef821dcc83675a7b814eb1c983222399a2f263ad980251201d1b9a99 languageName: node linkType: hard -"levelup@npm:3.1.1, levelup@npm:^3.0.0": - version: 3.1.1 - resolution: "levelup@npm:3.1.1" +"keyv@npm:^4.0.0": + version: 4.5.0 + resolution: "keyv@npm:4.5.0" dependencies: - deferred-leveldown: ~4.0.0 - level-errors: ~2.0.0 - level-iterator-stream: ~3.0.0 - xtend: ~4.0.0 - checksum: cddcac2cf5eddcf85ade62efd21f11326cd83559619db6a78696725eac5c5cd16f62d8d49f6594fd3097d9329a1d04847f6d7df23bf4d69f18c16e49afd4a416 + json-buffer: 3.0.1 + checksum: d294873cf88ec8f691e5edeb7b4b884f886c5f021a01902a0e243c362449db2b55419d7fb7187d059add747b7398321e39e44d391b65f94935174ce13452714d languageName: node linkType: hard -"levelup@npm:^1.2.1": - version: 1.3.9 - resolution: "levelup@npm:1.3.9" - dependencies: - deferred-leveldown: ~1.2.1 - level-codec: ~7.0.0 - level-errors: ~1.0.3 - level-iterator-stream: ~1.3.0 - prr: ~1.0.1 - semver: ~5.4.1 - xtend: ~4.0.0 - checksum: df3b534b948c17d724050f6ecc2b21eb2fde357bd0c68582cd3a5eb4bf943a3057cd2e9db6bd7253020fcb853c83a70943bff9264f5132afa8cf3c25c3c7cd8e +"kind-of@npm:^6.0.2": + version: 6.0.3 + resolution: "kind-of@npm:6.0.3" + checksum: 3ab01e7b1d440b22fe4c31f23d8d38b4d9b91d9f291df683476576493d5dfd2e03848a8b05813dd0c3f0e835bc63f433007ddeceb71f05cb25c45ae1b19c6d3b languageName: node linkType: hard -"levelup@npm:^4.3.2": - version: 4.4.0 - resolution: "levelup@npm:4.4.0" - dependencies: - deferred-leveldown: ~5.3.0 - level-errors: ~2.0.0 - level-iterator-stream: ~4.0.0 - level-supports: ~1.0.0 - xtend: ~4.0.0 - checksum: 5a09e34c78cd7c23f9f6cb73563f1ebe8121ffc5f9f5f232242529d4fbdd40e8d1ffb337d2defa0b842334e0dbd4028fbfe7a072eebfe2c4d07174f0aa4aabca +"kleur@npm:^3.0.3": + version: 3.0.3 + resolution: "kleur@npm:3.0.3" + checksum: df82cd1e172f957bae9c536286265a5cdbd5eeca487cb0a3b2a7b41ef959fc61f8e7c0e9aeea9c114ccf2c166b6a8dd45a46fd619c1c569d210ecd2765ad5169 languageName: node linkType: hard @@ -12509,19 +9862,6 @@ __metadata: languageName: node linkType: hard -"load-json-file@npm:^1.0.0": - version: 1.1.0 - resolution: "load-json-file@npm:1.1.0" - dependencies: - graceful-fs: ^4.1.2 - parse-json: ^2.2.0 - pify: ^2.0.0 - pinkie-promise: ^2.0.0 - strip-bom: ^2.0.0 - checksum: 0e4e4f380d897e13aa236246a917527ea5a14e4fc34d49e01ce4e7e2a1e08e2740ee463a03fb021c04f594f29a178f4adb994087549d7c1c5315fcd29bf9934b - languageName: node - linkType: hard - "locate-path@npm:^2.0.0": version: 2.0.0 resolution: "locate-path@npm:2.0.0" @@ -12551,13 +9891,6 @@ __metadata: languageName: node linkType: hard -"lodash.assign@npm:^4.0.3, lodash.assign@npm:^4.0.6": - version: 4.2.0 - resolution: "lodash.assign@npm:4.2.0" - checksum: 75bbc6733c9f577c448031b4051f990f068802708891f94be9d4c2faffd6a9ec67a2c49671dafc908a068d35687765464853282842b4560b662e6c903d11cc90 - languageName: node - linkType: hard - "lodash.camelcase@npm:^4.3.0": version: 4.3.0 resolution: "lodash.camelcase@npm:4.3.0" @@ -12691,13 +10024,6 @@ __metadata: languageName: node linkType: hard -"lodash@npm:4.17.20": - version: 4.17.20 - resolution: "lodash@npm:4.17.20" - checksum: b31afa09739b7292a88ec49ffdb2fcaeb41f690def010f7a067eeedffece32da6b6847bfe4d38a77e6f41778b9b2bca75eeab91209936518173271f0b69376ea - languageName: node - linkType: hard - "lodash@npm:^3.3.1": version: 3.10.1 resolution: "lodash@npm:3.10.1" @@ -12705,7 +10031,7 @@ __metadata: languageName: node linkType: hard -"lodash@npm:^4.17.11, lodash@npm:^4.17.12, lodash@npm:^4.17.14, lodash@npm:^4.17.15, lodash@npm:^4.17.16, lodash@npm:^4.17.19, lodash@npm:^4.17.21, lodash@npm:^4.17.4, lodash@npm:^4.5.1": +"lodash@npm:^4.17.11, lodash@npm:^4.17.12, lodash@npm:^4.17.14, lodash@npm:^4.17.15, lodash@npm:^4.17.16, lodash@npm:^4.17.19, lodash@npm:^4.17.21, lodash@npm:^4.5.1": version: 4.17.21 resolution: "lodash@npm:4.17.21" checksum: eb835a2e51d381e561e508ce932ea50a8e5a68f4ebdd771ea240d3048244a8d13658acbd502cd4829768c56f2e16bdd4340b9ea141297d472517b83868e677f7 @@ -12721,7 +10047,7 @@ __metadata: languageName: node linkType: hard -"log-symbols@npm:4.1.0": +"log-symbols@npm:4.1.0, log-symbols@npm:^4.1.0": version: 4.1.0 resolution: "log-symbols@npm:4.1.0" dependencies: @@ -12762,20 +10088,6 @@ __metadata: languageName: node linkType: hard -"looper@npm:^2.0.0": - version: 2.0.0 - resolution: "looper@npm:2.0.0" - checksum: ee5124d54c97cd9e778e602e297ed37dd6405b7c36830f90bb1aaa6adb8d64f2a228aa341459e6bf2db9a8d7dc9eb8c16ec9c6bffeab1c47f91efe213858ce36 - languageName: node - linkType: hard - -"looper@npm:^3.0.0": - version: 3.0.0 - resolution: "looper@npm:3.0.0" - checksum: 2ec29b4161e95d33f2257867b0b9ab7f2fef5425582362c966f8f9041a2a6032466b8be159af99323655aca9e6fe1c9da086cf208f6346bd97c9f83ab77ccce0 - languageName: node - linkType: hard - "loose-envify@npm:^1.0.0, loose-envify@npm:^1.1.0": version: 1.4.0 resolution: "loose-envify@npm:1.4.0" @@ -12796,13 +10108,6 @@ __metadata: languageName: node linkType: hard -"lowercase-keys@npm:^1.0.0, lowercase-keys@npm:^1.0.1": - version: 1.0.1 - resolution: "lowercase-keys@npm:1.0.1" - checksum: 4d045026595936e09953e3867722e309415ff2c80d7701d067546d75ef698dac218a4f53c6d1d0e7368b47e45fd7529df47e6cb56fbb90523ba599f898b3d147 - languageName: node - linkType: hard - "lowercase-keys@npm:^2.0.0": version: 2.0.0 resolution: "lowercase-keys@npm:2.0.0" @@ -12817,24 +10122,6 @@ __metadata: languageName: node linkType: hard -"lru-cache@npm:5.1.1, lru-cache@npm:^5.1.1": - version: 5.1.1 - resolution: "lru-cache@npm:5.1.1" - dependencies: - yallist: ^3.0.2 - checksum: c154ae1cbb0c2206d1501a0e94df349653c92c8cbb25236d7e85190bcaf4567a03ac6eb43166fabfa36fd35623694da7233e88d9601fbf411a9a481d85dbd2cb - languageName: node - linkType: hard - -"lru-cache@npm:^3.2.0": - version: 3.2.0 - resolution: "lru-cache@npm:3.2.0" - dependencies: - pseudomap: ^1.0.1 - checksum: 8e5fb3d7a83401165b8dc9fe16d74828df5754aaeda1061e4f2ea1d0e984b9071a6487f1c3f6f034f935429629f94366abbfb753827ab2977a56b3f5c276e736 - languageName: node - linkType: hard - "lru-cache@npm:^6.0.0": version: 6.0.0 resolution: "lru-cache@npm:6.0.0" @@ -12858,20 +10145,6 @@ __metadata: languageName: node linkType: hard -"ltgt@npm:^2.1.2, ltgt@npm:~2.2.0": - version: 2.2.1 - resolution: "ltgt@npm:2.2.1" - checksum: 7e3874296f7538bc8087b428ac4208008d7b76916354b34a08818ca7c83958c1df10ec427eeeaad895f6b81e41e24745b18d30f89abcc21d228b94f6961d50a2 - languageName: node - linkType: hard - -"ltgt@npm:~2.1.1": - version: 2.1.3 - resolution: "ltgt@npm:2.1.3" - checksum: b09281f6aeccb34eda52588d21f9116f6e5b7ae1c79f6180bba06edcdcba50de9c6d199be7f817a7ae59819064e3ca7d066fe0bcc67e2458006e4e45cd05cb11 - languageName: node - linkType: hard - "make-error@npm:^1.1.1": version: 1.3.6 resolution: "make-error@npm:1.3.6" @@ -12903,31 +10176,6 @@ __metadata: languageName: node linkType: hard -"map-age-cleaner@npm:^0.1.1": - version: 0.1.3 - resolution: "map-age-cleaner@npm:0.1.3" - dependencies: - p-defer: ^1.0.0 - checksum: cb2804a5bcb3cbdfe4b59066ea6d19f5e7c8c196cd55795ea4c28f792b192e4c442426ae52524e5e1acbccf393d3bddacefc3d41f803e66453f6c4eda3650bc1 - languageName: node - linkType: hard - -"map-cache@npm:^0.2.2": - version: 0.2.2 - resolution: "map-cache@npm:0.2.2" - checksum: 3067cea54285c43848bb4539f978a15dedc63c03022abeec6ef05c8cb6829f920f13b94bcaf04142fc6a088318e564c4785704072910d120d55dbc2e0c421969 - languageName: node - linkType: hard - -"map-visit@npm:^1.0.0": - version: 1.0.0 - resolution: "map-visit@npm:1.0.0" - dependencies: - object-visit: ^1.0.0 - checksum: c27045a5021c344fc19b9132eb30313e441863b2951029f8f8b66f79d3d8c1e7e5091578075a996f74e417479506fe9ede28c44ca7bc351a61c9d8073daec36a - languageName: node - linkType: hard - "markdown-table@npm:^1.1.3": version: 1.1.3 resolution: "markdown-table@npm:1.1.3" @@ -12953,13 +10201,6 @@ __metadata: languageName: node linkType: hard -"mcl-wasm@npm:^0.7.1": - version: 0.7.9 - resolution: "mcl-wasm@npm:0.7.9" - checksum: 6b6ed5084156b98b2db70b223e1ba2c01953970b48a2e0c4ea3eeb9296610e6b3bfb2a2cce9e92e2d7ad61778b5f5a630e705e663835e915ba188c174a0a37fa - languageName: node - linkType: hard - "md5.js@npm:^1.3.4": version: 1.3.5 resolution: "md5.js@npm:1.3.5" @@ -12978,59 +10219,6 @@ __metadata: languageName: node linkType: hard -"mem@npm:^4.0.0": - version: 4.3.0 - resolution: "mem@npm:4.3.0" - dependencies: - map-age-cleaner: ^0.1.1 - mimic-fn: ^2.0.0 - p-is-promise: ^2.0.0 - checksum: cf488608e5d59c6cb68004b70de317222d4be9f857fd535dfa6a108e04f40821479c080bc763c417b1030569d303538c59d441280078cfce07fefd1c523f98ef - languageName: node - linkType: hard - -"memdown@npm:^1.0.0": - version: 1.4.1 - resolution: "memdown@npm:1.4.1" - dependencies: - abstract-leveldown: ~2.7.1 - functional-red-black-tree: ^1.0.1 - immediate: ^3.2.3 - inherits: ~2.0.1 - ltgt: ~2.2.0 - safe-buffer: ~5.1.1 - checksum: 3f89142a12389b1ebfc7adaf3be19ed57cd073f84160eb7419b61c8e188e2b82eb787dad168d7b00ca68355b6b952067d9badaa5ac88c8ee014e4b0af2bfaea0 - languageName: node - linkType: hard - -"memdown@npm:^5.0.0": - version: 5.1.0 - resolution: "memdown@npm:5.1.0" - dependencies: - abstract-leveldown: ~6.2.1 - functional-red-black-tree: ~1.0.1 - immediate: ~3.2.3 - inherits: ~2.0.1 - ltgt: ~2.2.0 - safe-buffer: ~5.2.0 - checksum: 23e4414034e975eae1edd6864874bbe77501d41814fc27e8ead946c3379cb1cbea303d724083d08a6a269af9bf5d55073f1f767dfa7ad6e70465769f87e29794 - languageName: node - linkType: hard - -"memdown@npm:~3.0.0": - version: 3.0.0 - resolution: "memdown@npm:3.0.0" - dependencies: - abstract-leveldown: ~5.0.0 - functional-red-black-tree: ~1.0.1 - immediate: ~3.2.3 - inherits: ~2.0.1 - ltgt: ~2.2.0 - safe-buffer: ~5.1.1 - checksum: 4446fdf7198dcdbae764324200526f41738c9f2a32decb59b5a4dbb1bdfc72e2fc046e9bbe016469ab8a0a52e5d5c8b36bf3829e90dd4674a5f4c961e059d4de - languageName: node - linkType: hard - "memlet@npm:^0.1.7": version: 0.1.7 resolution: "memlet@npm:0.1.7" @@ -13042,17 +10230,6 @@ __metadata: languageName: node linkType: hard -"memory-level@npm:^1.0.0": - version: 1.0.0 - resolution: "memory-level@npm:1.0.0" - dependencies: - abstract-level: ^1.0.0 - functional-red-black-tree: ^1.0.1 - module-error: ^1.0.1 - checksum: 80b1b7aedaf936e754adbcd7b9303018c3684fb32f9992fd967c448f145d177f16c724fbba9ed3c3590a9475fd563151eae664d69b83d2ad48714852e9fc5c72 - languageName: node - linkType: hard - "memorystream@npm:^0.3.1": version: 0.3.1 resolution: "memorystream@npm:0.3.1" @@ -13090,51 +10267,6 @@ __metadata: languageName: node linkType: hard -"merkle-patricia-tree@npm:3.0.0": - version: 3.0.0 - resolution: "merkle-patricia-tree@npm:3.0.0" - dependencies: - async: ^2.6.1 - ethereumjs-util: ^5.2.0 - level-mem: ^3.0.1 - level-ws: ^1.0.0 - readable-stream: ^3.0.6 - rlp: ^2.0.0 - semaphore: ">=1.0.1" - checksum: a500f00e7954eea132309310c48ee2635e9a190e0a775811236a0dc375465ff7e01b230ac0ee213ca13bb995399066719eedb4218e0f47596e9cab79cebc575e - languageName: node - linkType: hard - -"merkle-patricia-tree@npm:^2.1.2, merkle-patricia-tree@npm:^2.3.2": - version: 2.3.2 - resolution: "merkle-patricia-tree@npm:2.3.2" - dependencies: - async: ^1.4.2 - ethereumjs-util: ^5.0.0 - level-ws: 0.0.0 - levelup: ^1.2.1 - memdown: ^1.0.0 - readable-stream: ^2.0.0 - rlp: ^2.0.0 - semaphore: ">=1.0.1" - checksum: f6066a16e08190b9e8d3aa28d8e861a3e884ee0be8109c4f5e879965fdfb8181cfc04bae3aaf97c7fb6d07446d94b4f3e1cce502dde4a5699a03acf6df518b12 - languageName: node - linkType: hard - -"merkle-patricia-tree@npm:^4.2.4": - version: 4.2.4 - resolution: "merkle-patricia-tree@npm:4.2.4" - dependencies: - "@types/levelup": ^4.3.0 - ethereumjs-util: ^7.1.4 - level-mem: ^5.0.1 - level-ws: ^2.0.0 - readable-stream: ^3.6.0 - semaphore-async-await: ^1.5.1 - checksum: acedc7eea7bb14b97da01e8e023406ed55742f8e82bdd28d1ed821e3bd0cfed9e92f18c7cb300aee0d38f319c960026fd4d4e601f61e2a8665b73c0786d9f799 - languageName: node - linkType: hard - "methods@npm:~1.1.2": version: 1.1.2 resolution: "methods@npm:1.1.2" @@ -13142,34 +10274,30 @@ __metadata: languageName: node linkType: hard -"micromatch@npm:^3.1.4": - version: 3.1.10 - resolution: "micromatch@npm:3.1.10" +"micro-eth-signer@npm:^0.14.0": + version: 0.14.0 + resolution: "micro-eth-signer@npm:0.14.0" dependencies: - arr-diff: ^4.0.0 - array-unique: ^0.3.2 - braces: ^2.3.1 - define-property: ^2.0.2 - extend-shallow: ^3.0.2 - extglob: ^2.0.4 - fragment-cache: ^0.2.1 - kind-of: ^6.0.2 - nanomatch: ^1.2.9 - object.pick: ^1.3.0 - regex-not: ^1.0.0 - snapdragon: ^0.8.1 - to-regex: ^3.0.2 - checksum: ad226cba4daa95b4eaf47b2ca331c8d2e038d7b41ae7ed0697cde27f3f1d6142881ab03d4da51b65d9d315eceb5e4cdddb3fbb55f5f72cfa19cf3ea469d054dc + "@noble/curves": ~1.8.1 + "@noble/hashes": ~1.7.1 + micro-packed: ~0.7.2 + checksum: 9f49282ed8d0057c77cb65ee87a7c08909cf25ae62676c9ff8006d804bbd882dd2f56956e8589e3716ec7c647a9f308f45810c1f40416873f352a59941a17d7b + languageName: node + linkType: hard + +"micro-ftch@npm:^0.3.1": + version: 0.3.1 + resolution: "micro-ftch@npm:0.3.1" + checksum: 0e496547253a36e98a83fb00c628c53c3fb540fa5aaeaf718438873785afd193244988c09d219bb1802984ff227d04938d9571ef90fe82b48bd282262586aaff languageName: node linkType: hard -"micromatch@npm:^4.0.2": - version: 4.0.5 - resolution: "micromatch@npm:4.0.5" +"micro-packed@npm:~0.7.2": + version: 0.7.3 + resolution: "micro-packed@npm:0.7.3" dependencies: - braces: ^3.0.2 - picomatch: ^2.3.1 - checksum: 02a17b671c06e8fefeeb6ef996119c1e597c942e632a21ef589154f23898c9c6a9858526246abb14f8bca6e77734aa9dcf65476fca47cedfb80d9577d52843fc + "@scure/base": ~1.2.5 + checksum: ad622288c56bacd9d7fe177e4b351c7a58e23f08e8cec2c9106f1c9da8e88d51101d667ed95d3f57979b520917b86edda43175ff4b5c8dcd5b96db7102865fa8 languageName: node linkType: hard @@ -13243,14 +10371,14 @@ __metadata: languageName: node linkType: hard -"mimic-fn@npm:^2.0.0, mimic-fn@npm:^2.1.0": +"mimic-fn@npm:^2.1.0": version: 2.1.0 resolution: "mimic-fn@npm:2.1.0" checksum: d2421a3444848ce7f84bd49115ddacff29c15745db73f54041edc906c14b131a38d05298dae3081667627a59b2eb1ca4b436ff2e1b80f69679522410418b478a languageName: node linkType: hard -"mimic-response@npm:^1.0.0, mimic-response@npm:^1.0.1": +"mimic-response@npm:^1.0.0": version: 1.0.1 resolution: "mimic-response@npm:1.0.1" checksum: 034c78753b0e622bc03c983663b1cdf66d03861050e0c8606563d149bc2b02d63f62ce4d32be4ab50d0553ae0ffe647fc34d1f5281184c6e1e8cf4d85e8d9823 @@ -13332,6 +10460,15 @@ __metadata: languageName: node linkType: hard +"minimatch@npm:^5.1.6": + version: 5.1.9 + resolution: "minimatch@npm:5.1.9" + dependencies: + brace-expansion: ^2.0.1 + checksum: 418438bd7701ba811f1108f28fcd3a638a6065c7b1245b85e25bcdb674410b4bebd8763c90c91bc8d22d93260c02cc129b354267a463c3399be5732d6e11e120 + languageName: node + linkType: hard + "minimatch@npm:^7.4.1": version: 7.4.2 resolution: "minimatch@npm:7.4.2" @@ -13350,6 +10487,15 @@ __metadata: languageName: node linkType: hard +"minimatch@npm:^9.0.4": + version: 9.0.9 + resolution: "minimatch@npm:9.0.9" + dependencies: + brace-expansion: ^2.0.2 + checksum: 5292681ba1e14544ca9214ba5e412bb346214fb783354b22752f2d1e5c176e4a2c0bfcafeb1046389b816009ab73ba5410b176ce605632e8aa695db25f87f6b9 + languageName: node + linkType: hard + "minimist@npm:^1.2.0, minimist@npm:^1.2.3, minimist@npm:^1.2.5": version: 1.2.5 resolution: "minimist@npm:1.2.5" @@ -13357,7 +10503,7 @@ __metadata: languageName: node linkType: hard -"minimist@npm:^1.2.6, minimist@npm:~1.2.6": +"minimist@npm:^1.2.6": version: 1.2.7 resolution: "minimist@npm:1.2.7" checksum: 7346574a1038ca23c32e02252f603801f09384dd1d78b69a943a4e8c2c28730b80e96193882d3d3b22a063445f460e48316b29b8a25addca2d7e5e8f75478bec @@ -13467,16 +10613,6 @@ __metadata: languageName: node linkType: hard -"mixin-deep@npm:^1.2.0": - version: 1.3.2 - resolution: "mixin-deep@npm:1.3.2" - dependencies: - for-in: ^1.0.2 - is-extendable: ^1.0.1 - checksum: 820d5a51fcb7479f2926b97f2c3bb223546bc915e6b3a3eb5d906dda871bba569863595424a76682f2b15718252954644f3891437cb7e3f220949bed54b1750d - languageName: node - linkType: hard - "mkdirp-classic@npm:^0.5.2, mkdirp-classic@npm:^0.5.3": version: 0.5.3 resolution: "mkdirp-classic@npm:0.5.3" @@ -13575,6 +10711,37 @@ __metadata: languageName: node linkType: hard +"mocha@npm:^10.2.0": + version: 10.8.2 + resolution: "mocha@npm:10.8.2" + dependencies: + ansi-colors: ^4.1.3 + browser-stdout: ^1.3.1 + chokidar: ^3.5.3 + debug: ^4.3.5 + diff: ^5.2.0 + escape-string-regexp: ^4.0.0 + find-up: ^5.0.0 + glob: ^8.1.0 + he: ^1.2.0 + js-yaml: ^4.1.0 + log-symbols: ^4.1.0 + minimatch: ^5.1.6 + ms: ^2.1.3 + serialize-javascript: ^6.0.2 + strip-json-comments: ^3.1.1 + supports-color: ^8.1.1 + workerpool: ^6.5.1 + yargs: ^16.2.0 + yargs-parser: ^20.2.9 + yargs-unparser: ^2.0.0 + bin: + _mocha: bin/_mocha + mocha: bin/mocha.js + checksum: 68cb519503f1e8ffd9b0651e1aef75dfe4754425186756b21e53169da44b5bcb1889e2b743711205082763d3f9a42eb8eb2c13bb1a718a08cb3a5f563bfcacdc + languageName: node + linkType: hard + "mocha@npm:^7.1.1": version: 7.2.0 resolution: "mocha@npm:7.2.0" @@ -13652,13 +10819,6 @@ __metadata: languageName: node linkType: hard -"module-error@npm:^1.0.1, module-error@npm:^1.0.2": - version: 1.0.2 - resolution: "module-error@npm:1.0.2" - checksum: 5d653e35bd55b3e95f8aee2cdac108082ea892e71b8f651be92cde43e4ee86abee4fa8bd7fc3fe5e68b63926d42f63c54cd17b87a560c31f18739295575a3962 - languageName: node - linkType: hard - "moment@npm:^2.29.1": version: 2.29.4 resolution: "moment@npm:2.29.4" @@ -13687,7 +10847,7 @@ __metadata: languageName: node linkType: hard -"ms@npm:2.1.3, ms@npm:^2.0.0, ms@npm:^2.1.1": +"ms@npm:2.1.3, ms@npm:^2.0.0, ms@npm:^2.1.1, ms@npm:^2.1.3": version: 2.1.3 resolution: "ms@npm:2.1.3" checksum: aa92de608021b242401676e35cfa5aa42dd70cbdc082b916da7fb925c542173e36bce97ea3e804923fe92c0ad991434e4a38327e15a1b5b5f945d66df615ae6d @@ -13842,25 +11002,6 @@ __metadata: languageName: node linkType: hard -"nanomatch@npm:^1.2.9": - version: 1.2.13 - resolution: "nanomatch@npm:1.2.13" - dependencies: - arr-diff: ^4.0.0 - array-unique: ^0.3.2 - define-property: ^2.0.2 - extend-shallow: ^3.0.2 - fragment-cache: ^0.2.1 - is-windows: ^1.0.2 - kind-of: ^6.0.2 - object.pick: ^1.3.0 - regex-not: ^1.0.0 - snapdragon: ^0.8.1 - to-regex: ^3.0.1 - checksum: 54d4166d6ef08db41252eb4e96d4109ebcb8029f0374f9db873bd91a1f896c32ec780d2a2ea65c0b2d7caf1f28d5e1ea33746a470f32146ac8bba821d80d38d8 - languageName: node - linkType: hard - "napi-build-utils@npm:^1.0.1": version: 1.0.2 resolution: "napi-build-utils@npm:1.0.2" @@ -13868,13 +11009,6 @@ __metadata: languageName: node linkType: hard -"napi-macros@npm:~2.0.0": - version: 2.0.0 - resolution: "napi-macros@npm:2.0.0" - checksum: 30384819386977c1f82034757014163fa60ab3c5a538094f778d38788bebb52534966279956f796a92ea771c7f8ae072b975df65de910d051ffbdc927f62320c - languageName: node - linkType: hard - "native-abort-controller@npm:^1.0.3, native-abort-controller@npm:^1.0.4": version: 1.0.4 resolution: "native-abort-controller@npm:1.0.4" @@ -13997,7 +11131,7 @@ __metadata: languageName: node linkType: hard -"node-fetch@npm:2.6.7, node-fetch@npm:^2.6.1, node-fetch@npm:^2.6.7": +"node-fetch@npm:2.6.7, node-fetch@npm:^2.6.1": version: 2.6.7 resolution: "node-fetch@npm:2.6.7" dependencies: @@ -14039,16 +11173,6 @@ __metadata: languageName: node linkType: hard -"node-fetch@npm:~1.7.1": - version: 1.7.3 - resolution: "node-fetch@npm:1.7.3" - dependencies: - encoding: ^0.1.11 - is-stream: ^1.0.1 - checksum: 3bb0528c05d541316ebe52770d71ee25a6dce334df4231fd55df41a644143e07f068637488c18a5b0c43f05041dbd3346752f9e19b50df50569a802484544d5b - languageName: node - linkType: hard - "node-gyp-build@npm:^4.2.0": version: 4.3.0 resolution: "node-gyp-build@npm:4.3.0" @@ -14159,18 +11283,6 @@ __metadata: languageName: node linkType: hard -"normalize-package-data@npm:^2.3.2": - version: 2.5.0 - resolution: "normalize-package-data@npm:2.5.0" - dependencies: - hosted-git-info: ^2.1.4 - resolve: ^1.10.0 - semver: 2 || 3 || 4 || 5 - validate-npm-package-license: ^3.0.1 - checksum: 7999112efc35a6259bc22db460540cae06564aa65d0271e3bdfa86876d08b0e578b7b5b0028ee61b23f1cae9fc0e7847e4edc0948d3068a39a2a82853efc8499 - languageName: node - linkType: hard - "normalize-path@npm:^3.0.0, normalize-path@npm:~3.0.0": version: 3.0.0 resolution: "normalize-path@npm:3.0.0" @@ -14178,13 +11290,6 @@ __metadata: languageName: node linkType: hard -"normalize-url@npm:^4.1.0": - version: 4.5.1 - resolution: "normalize-url@npm:4.5.1" - checksum: 9a9dee01df02ad23e171171893e56e22d752f7cff86fb96aafeae074819b572ea655b60f8302e2d85dbb834dc885c972cc1c573892fea24df46b2765065dd05a - languageName: node - linkType: hard - "normalize-url@npm:^6.0.1": version: 6.1.0 resolution: "normalize-url@npm:6.1.0" @@ -14192,15 +11297,6 @@ __metadata: languageName: node linkType: hard -"npm-run-path@npm:^2.0.0": - version: 2.0.2 - resolution: "npm-run-path@npm:2.0.2" - dependencies: - path-key: ^2.0.0 - checksum: acd5ad81648ba4588ba5a8effb1d98d2b339d31be16826a118d50f182a134ac523172101b82eab1d01cb4c2ba358e857d54cfafd8163a1ffe7bd52100b741125 - languageName: node - linkType: hard - "npm-run-path@npm:^4.0.1": version: 4.0.1 resolution: "npm-run-path@npm:4.0.1" @@ -14246,21 +11342,10 @@ __metadata: languageName: node linkType: hard -"object-assign@npm:^4, object-assign@npm:^4.0.0, object-assign@npm:^4.1.0, object-assign@npm:^4.1.1": - version: 4.1.1 - resolution: "object-assign@npm:4.1.1" - checksum: fcc6e4ea8c7fe48abfbb552578b1c53e0d194086e2e6bbbf59e0a536381a292f39943c6e9628af05b5528aa5e3318bb30d6b2e53cadaf5b8fe9e12c4b69af23f - languageName: node - linkType: hard - -"object-copy@npm:^0.1.0": - version: 0.1.0 - resolution: "object-copy@npm:0.1.0" - dependencies: - copy-descriptor: ^0.1.0 - define-property: ^0.2.5 - kind-of: ^3.0.3 - checksum: a9e35f07e3a2c882a7e979090360d1a20ab51d1fa19dfdac3aa8873b328a7c4c7683946ee97c824ae40079d848d6740a3788fa14f2185155dab7ed970a72c783 +"object-assign@npm:^4, object-assign@npm:^4.1.0, object-assign@npm:^4.1.1": + version: 4.1.1 + resolution: "object-assign@npm:4.1.1" + checksum: fcc6e4ea8c7fe48abfbb552578b1c53e0d194086e2e6bbbf59e0a536381a292f39943c6e9628af05b5528aa5e3318bb30d6b2e53cadaf5b8fe9e12c4b69af23f languageName: node linkType: hard @@ -14271,7 +11356,7 @@ __metadata: languageName: node linkType: hard -"object-inspect@npm:^1.12.2, object-inspect@npm:~1.12.2": +"object-inspect@npm:^1.12.2": version: 1.12.2 resolution: "object-inspect@npm:1.12.2" checksum: a534fc1b8534284ed71f25ce3a496013b7ea030f3d1b77118f6b7b1713829262be9e6243acbcb3ef8c626e2b64186112cb7f6db74e37b2789b9c789ca23048b2 @@ -14285,16 +11370,6 @@ __metadata: languageName: node linkType: hard -"object-is@npm:^1.0.1": - version: 1.1.5 - resolution: "object-is@npm:1.1.5" - dependencies: - call-bind: ^1.0.2 - define-properties: ^1.1.3 - checksum: 989b18c4cba258a6b74dc1d74a41805c1a1425bce29f6cabb50dcb1a6a651ea9104a1b07046739a49a5bb1bc49727bcb00efd5c55f932f6ea04ec8927a7901fe - languageName: node - linkType: hard - "object-keys@npm:^1.0.11, object-keys@npm:^1.0.12, object-keys@npm:^1.1.1": version: 1.1.1 resolution: "object-keys@npm:1.1.1" @@ -14302,13 +11377,6 @@ __metadata: languageName: node linkType: hard -"object-keys@npm:~0.4.0": - version: 0.4.0 - resolution: "object-keys@npm:0.4.0" - checksum: 1be3ebe9b48c0d5eda8e4a30657d887a748cb42435e0e2eaf49faf557bdd602cd2b7558b8ce90a4eb2b8592d16b875a1900bce859cbb0f35b21c67e11a45313c - languageName: node - linkType: hard - "object-treeify@npm:^1.1.33": version: 1.1.33 resolution: "object-treeify@npm:1.1.33" @@ -14316,15 +11384,6 @@ __metadata: languageName: node linkType: hard -"object-visit@npm:^1.0.0": - version: 1.0.1 - resolution: "object-visit@npm:1.0.1" - dependencies: - isobject: ^3.0.0 - checksum: b0ee07f5bf3bb881b881ff53b467ebbde2b37ebb38649d6944a6cd7681b32eedd99da9bd1e01c55facf81f54ed06b13af61aba6ad87f0052982995e09333f790 - languageName: node - linkType: hard - "object.assign@npm:4.1.0": version: 4.1.0 resolution: "object.assign@npm:4.1.0" @@ -14361,7 +11420,7 @@ __metadata: languageName: node linkType: hard -"object.getownpropertydescriptors@npm:^2.0.3, object.getownpropertydescriptors@npm:^2.1.1": +"object.getownpropertydescriptors@npm:^2.0.3": version: 2.1.4 resolution: "object.getownpropertydescriptors@npm:2.1.4" dependencies: @@ -14373,15 +11432,6 @@ __metadata: languageName: node linkType: hard -"object.pick@npm:^1.3.0": - version: 1.3.0 - resolution: "object.pick@npm:1.3.0" - dependencies: - isobject: ^3.0.1 - checksum: 77fb6eed57c67adf75e9901187e37af39f052ef601cb4480386436561357eb9e459e820762f01fd02c5c1b42ece839ad393717a6d1850d848ee11fbabb3e580a - languageName: node - linkType: hard - "object.values@npm:^1.1.5": version: 1.1.5 resolution: "object.values@npm:1.1.5" @@ -14400,15 +11450,6 @@ __metadata: languageName: node linkType: hard -"oboe@npm:2.1.4": - version: 2.1.4 - resolution: "oboe@npm:2.1.4" - dependencies: - http-https: ^1.0.0 - checksum: b9172453fba362aec86c45d7bcb4f512302bb23ef34c7c9c498974dc4e7ec0e298931bac5a093445fd946d5604e5dd16563e2d2ae922101ac4b47be2e18e30cc - languageName: node - linkType: hard - "oboe@npm:2.1.5": version: 2.1.5 resolution: "oboe@npm:2.1.5" @@ -14461,16 +11502,6 @@ __metadata: languageName: node linkType: hard -"open@npm:^7.4.2": - version: 7.4.2 - resolution: "open@npm:7.4.2" - dependencies: - is-docker: ^2.0.0 - is-wsl: ^2.1.1 - checksum: 3333900ec0e420d64c23b831bc3467e57031461d843c801f569b2204a1acc3cd7b3ec3c7897afc9dde86491dfa289708eb92bba164093d8bd88fb2c231843c91 - languageName: node - linkType: hard - "optionator@npm:^0.8.1, optionator@npm:^0.8.2": version: 0.8.3 resolution: "optionator@npm:0.8.3" @@ -14485,17 +11516,17 @@ __metadata: languageName: node linkType: hard -"optionator@npm:^0.9.1": - version: 0.9.1 - resolution: "optionator@npm:0.9.1" +"optionator@npm:^0.9.3": + version: 0.9.4 + resolution: "optionator@npm:0.9.4" dependencies: deep-is: ^0.1.3 fast-levenshtein: ^2.0.6 levn: ^0.4.1 prelude-ls: ^1.2.1 type-check: ^0.4.0 - word-wrap: ^1.2.3 - checksum: dbc6fa065604b24ea57d734261914e697bd73b69eff7f18e967e8912aa2a40a19a9f599a507fa805be6c13c24c4eae8c71306c239d517d42d4c041c942f508a0 + word-wrap: ^1.2.5 + checksum: ecbd010e3dc73e05d239976422d9ef54a82a13f37c11ca5911dff41c98a6c7f0f163b27f922c37e7f8340af9d36febd3b6e9cef508f3339d4c393d7276d716bb languageName: node linkType: hard @@ -14514,34 +11545,7 @@ __metadata: languageName: node linkType: hard -"os-homedir@npm:^1.0.0": - version: 1.0.2 - resolution: "os-homedir@npm:1.0.2" - checksum: af609f5a7ab72de2f6ca9be6d6b91a599777afc122ac5cad47e126c1f67c176fe9b52516b9eeca1ff6ca0ab8587fe66208bc85e40a3940125f03cdb91408e9d2 - languageName: node - linkType: hard - -"os-locale@npm:^1.4.0": - version: 1.4.0 - resolution: "os-locale@npm:1.4.0" - dependencies: - lcid: ^1.0.0 - checksum: 0161a1b6b5a8492f99f4b47fe465df9fc521c55ba5414fce6444c45e2500487b8ed5b40a47a98a2363fe83ff04ab033785300ed8df717255ec4c3b625e55b1fb - languageName: node - linkType: hard - -"os-locale@npm:^3.1.0": - version: 3.1.0 - resolution: "os-locale@npm:3.1.0" - dependencies: - execa: ^1.0.0 - lcid: ^2.0.0 - mem: ^4.0.0 - checksum: 53c542b11af3c5fe99624b09c7882b6944f9ae7c69edbc6006b7d42cff630b1f7fd9d63baf84ed31d1ef02b34823b6b31f23a1ecdd593757873d716bc6374099 - languageName: node - linkType: hard - -"os-tmpdir@npm:^1.0.1, os-tmpdir@npm:~1.0.2": +"os-tmpdir@npm:~1.0.2": version: 1.0.2 resolution: "os-tmpdir@npm:1.0.2" checksum: 5666560f7b9f10182548bf7013883265be33620b1c1b4a4d405c25be2636f970c5488ff3e6c48de75b55d02bde037249fe5dbfbb4c0fb7714953d56aed062e6d @@ -14569,13 +11573,6 @@ __metadata: languageName: node linkType: hard -"p-cancelable@npm:^1.0.0": - version: 1.1.0 - resolution: "p-cancelable@npm:1.1.0" - checksum: 2db3814fef6d9025787f30afaee4496a8857a28be3c5706432cbad76c688a6db1874308f48e364a42f5317f5e41e8e7b4f2ff5c8ff2256dbb6264bc361704ece - languageName: node - linkType: hard - "p-cancelable@npm:^2.0.0": version: 2.1.1 resolution: "p-cancelable@npm:2.1.1" @@ -14590,13 +11587,6 @@ __metadata: languageName: node linkType: hard -"p-defer@npm:^1.0.0": - version: 1.0.0 - resolution: "p-defer@npm:1.0.0" - checksum: 4271b935c27987e7b6f229e5de4cdd335d808465604644cb7b4c4c95bef266735859a93b16415af8a41fd663ee9e3b97a1a2023ca9def613dba1bad2a0da0c7b - languageName: node - linkType: hard - "p-defer@npm:^3.0.0": version: 3.0.0 resolution: "p-defer@npm:3.0.0" @@ -14614,20 +11604,6 @@ __metadata: languageName: node linkType: hard -"p-finally@npm:^1.0.0": - version: 1.0.0 - resolution: "p-finally@npm:1.0.0" - checksum: 93a654c53dc805dd5b5891bab16eb0ea46db8f66c4bfd99336ae929323b1af2b70a8b0654f8f1eae924b2b73d037031366d645f1fd18b3d30cbd15950cc4b1d4 - languageName: node - linkType: hard - -"p-is-promise@npm:^2.0.0": - version: 2.1.0 - resolution: "p-is-promise@npm:2.1.0" - checksum: c9a8248c8b5e306475a5d55ce7808dbce4d4da2e3d69526e4991a391a7809bfd6cfdadd9bf04f1c96a3db366c93d9a0f5ee81d949e7b1684c4e0f61f747199ef - languageName: node - linkType: hard - "p-limit@npm:^1.1.0": version: 1.3.0 resolution: "p-limit@npm:1.3.0" @@ -14748,15 +11724,6 @@ __metadata: languageName: node linkType: hard -"parse-json@npm:^2.2.0": - version: 2.2.0 - resolution: "parse-json@npm:2.2.0" - dependencies: - error-ex: ^1.2.0 - checksum: dda78a63e57a47b713a038630868538f718a7ca0cd172a36887b0392ccf544ed0374902eb28f8bf3409e8b71d62b79d17062f8543afccf2745f9b0b2d2bb80ca - languageName: node - linkType: hard - "parse-json@npm:^4.0.0": version: 4.0.0 resolution: "parse-json@npm:4.0.0" @@ -14786,13 +11753,6 @@ __metadata: languageName: node linkType: hard -"pascalcase@npm:^0.1.1": - version: 0.1.1 - resolution: "pascalcase@npm:0.1.1" - checksum: f83681c3c8ff75fa473a2bb2b113289952f802ff895d435edd717e7cb898b0408cbdb247117a938edcbc5d141020909846cc2b92c47213d764e2a94d2ad2b925 - languageName: node - linkType: hard - "password-prompt@npm:^1.1.2": version: 1.1.2 resolution: "password-prompt@npm:1.1.2" @@ -14803,68 +11763,6 @@ __metadata: languageName: node linkType: hard -"patch-package@npm:6.2.2": - version: 6.2.2 - resolution: "patch-package@npm:6.2.2" - dependencies: - "@yarnpkg/lockfile": ^1.1.0 - chalk: ^2.4.2 - cross-spawn: ^6.0.5 - find-yarn-workspace-root: ^1.2.1 - fs-extra: ^7.0.1 - is-ci: ^2.0.0 - klaw-sync: ^6.0.0 - minimist: ^1.2.0 - rimraf: ^2.6.3 - semver: ^5.6.0 - slash: ^2.0.0 - tmp: ^0.0.33 - bin: - patch-package: index.js - checksum: 5e2f49457b0dc56b5ce0a9d23e281e062e9f225d87a832540f02ffed29ffa7f298b1877daf13c16500ef8a759109c975e3d28d6bd63b0d953f349177abee1767 - languageName: node - linkType: hard - -"patch-package@npm:^6.2.2": - version: 6.5.0 - resolution: "patch-package@npm:6.5.0" - dependencies: - "@yarnpkg/lockfile": ^1.1.0 - chalk: ^4.1.2 - cross-spawn: ^6.0.5 - find-yarn-workspace-root: ^2.0.0 - fs-extra: ^7.0.1 - is-ci: ^2.0.0 - klaw-sync: ^6.0.0 - minimist: ^1.2.6 - open: ^7.4.2 - rimraf: ^2.6.3 - semver: ^5.6.0 - slash: ^2.0.0 - tmp: ^0.0.33 - yaml: ^1.10.2 - bin: - patch-package: index.js - checksum: d300e87617e3fb990d1f78fd5be205b5a5e65dfdf197b1e7f76f3b3dfe1551a03d276cb5ee6b82ab4d57e78f54ddc22bde803eec1b0896560262b276d0b2c4ab - languageName: node - linkType: hard - -"path-browserify@npm:^1.0.0": - version: 1.0.1 - resolution: "path-browserify@npm:1.0.1" - checksum: c6d7fa376423fe35b95b2d67990060c3ee304fc815ff0a2dc1c6c3cfaff2bd0d572ee67e18f19d0ea3bbe32e8add2a05021132ac40509416459fffee35200699 - languageName: node - linkType: hard - -"path-exists@npm:^2.0.0": - version: 2.1.0 - resolution: "path-exists@npm:2.1.0" - dependencies: - pinkie-promise: ^2.0.0 - checksum: fdb734f1d00f225f7a0033ce6d73bff6a7f76ea08936abf0e5196fa6e54a645103538cd8aedcb90d6d8c3fa3705ded0c58a4da5948ae92aa8834892c1ab44a84 - languageName: node - linkType: hard - "path-exists@npm:^3.0.0": version: 3.0.0 resolution: "path-exists@npm:3.0.0" @@ -14879,7 +11777,7 @@ __metadata: languageName: node linkType: hard -"path-is-absolute@npm:^1.0.0, path-is-absolute@npm:^1.0.1": +"path-is-absolute@npm:^1.0.0": version: 1.0.1 resolution: "path-is-absolute@npm:1.0.1" checksum: 060840f92cf8effa293bcc1bea81281bd7d363731d214cbe5c227df207c34cd727430f70c6037b5159c8a870b9157cba65e775446b0ab06fd5ecc7e54615a3b8 @@ -14893,7 +11791,7 @@ __metadata: languageName: node linkType: hard -"path-key@npm:^2.0.0, path-key@npm:^2.0.1": +"path-key@npm:^2.0.1": version: 2.0.1 resolution: "path-key@npm:2.0.1" checksum: f7ab0ad42fe3fb8c7f11d0c4f849871e28fbd8e1add65c370e422512fc5887097b9cf34d09c1747d45c942a8c1e26468d6356e2df3f740bf177ab8ca7301ebfd @@ -14907,7 +11805,7 @@ __metadata: languageName: node linkType: hard -"path-parse@npm:^1.0.6, path-parse@npm:^1.0.7": +"path-parse@npm:^1.0.6": version: 1.0.7 resolution: "path-parse@npm:1.0.7" checksum: 49abf3d81115642938a8700ec580da6e830dde670be21893c62f4e10bd7dd4c3742ddc603fe24f898cba7eb0c6bc1777f8d9ac14185d34540c6d4d80cd9cae8a @@ -14931,17 +11829,6 @@ __metadata: languageName: node linkType: hard -"path-type@npm:^1.0.0": - version: 1.1.0 - resolution: "path-type@npm:1.1.0" - dependencies: - graceful-fs: ^4.1.2 - pify: ^2.0.0 - pinkie-promise: ^2.0.0 - checksum: 59a4b2c0e566baf4db3021a1ed4ec09a8b36fca960a490b54a6bcefdb9987dafe772852982b6011cd09579478a96e57960a01f75fa78a794192853c9d468fc79 - languageName: node - linkType: hard - "path-type@npm:^4.0.0": version: 4.0.0 resolution: "path-type@npm:4.0.0" @@ -14956,7 +11843,7 @@ __metadata: languageName: node linkType: hard -"pbkdf2@npm:^3.0.17, pbkdf2@npm:^3.0.3, pbkdf2@npm:^3.0.9": +"pbkdf2@npm:^3.0.17, pbkdf2@npm:^3.0.3": version: 3.1.2 resolution: "pbkdf2@npm:3.1.2" dependencies: @@ -14976,6 +11863,13 @@ __metadata: languageName: node linkType: hard +"picocolors@npm:^1.1.0": + version: 1.1.1 + resolution: "picocolors@npm:1.1.1" + checksum: e1cf46bf84886c79055fdfa9dcb3e4711ad259949e3565154b004b260cd356c5d54b31a1437ce9782624bf766272fe6b0154f5f0c744fb7af5d454d2b60db045 + languageName: node + linkType: hard + "picomatch@npm:^2.0.4, picomatch@npm:^2.2.1, picomatch@npm:^2.2.3": version: 2.3.0 resolution: "picomatch@npm:2.3.0" @@ -14983,17 +11877,10 @@ __metadata: languageName: node linkType: hard -"picomatch@npm:^2.3.1": - version: 2.3.1 - resolution: "picomatch@npm:2.3.1" - checksum: 050c865ce81119c4822c45d3c84f1ced46f93a0126febae20737bd05ca20589c564d6e9226977df859ed5e03dc73f02584a2b0faad36e896936238238b0446cf - languageName: node - linkType: hard - -"pify@npm:^2.0.0, pify@npm:^2.3.0": - version: 2.3.0 - resolution: "pify@npm:2.3.0" - checksum: 9503aaeaf4577acc58642ad1d25c45c6d90288596238fb68f82811c08104c800e5a7870398e9f015d82b44ecbcbef3dc3d4251a1cbb582f6e5959fe09884b2ba +"picomatch@npm:^4.0.3": + version: 4.0.3 + resolution: "picomatch@npm:4.0.3" + checksum: 6817fb74eb745a71445debe1029768de55fd59a42b75606f478ee1d0dc1aa6e78b711d041a7c9d5550e042642029b7f373dc1a43b224c4b7f12d23436735dba0 languageName: node linkType: hard @@ -15004,22 +11891,6 @@ __metadata: languageName: node linkType: hard -"pinkie-promise@npm:^2.0.0": - version: 2.0.1 - resolution: "pinkie-promise@npm:2.0.1" - dependencies: - pinkie: ^2.0.0 - checksum: b53a4a2e73bf56b6f421eef711e7bdcb693d6abb474d57c5c413b809f654ba5ee750c6a96dd7225052d4b96c4d053cdcb34b708a86fceed4663303abee52fcca - languageName: node - linkType: hard - -"pinkie@npm:^2.0.0": - version: 2.0.4 - resolution: "pinkie@npm:2.0.4" - checksum: b12b10afea1177595aab036fc220785488f67b4b0fc49e7a27979472592e971614fa1c728e63ad3e7eb748b4ec3c3dbd780819331dad6f7d635c77c10537b9db - languageName: node - linkType: hard - "pkg-dir@npm:^2.0.0": version: 2.0.0 resolution: "pkg-dir@npm:2.0.0" @@ -15036,20 +11907,6 @@ __metadata: languageName: node linkType: hard -"posix-character-classes@npm:^0.1.0": - version: 0.1.1 - resolution: "posix-character-classes@npm:0.1.1" - checksum: dedb99913c60625a16050cfed2fb5c017648fc075be41ac18474e1c6c3549ef4ada201c8bd9bd006d36827e289c571b6092e1ef6e756cdbab2fd7046b25c6442 - languageName: node - linkType: hard - -"postinstall-postinstall@npm:^2.1.0": - version: 2.1.0 - resolution: "postinstall-postinstall@npm:2.1.0" - checksum: e1d34252cf8d2c5641c7d2db7426ec96e3d7a975f01c174c68f09ef5b8327bc8d5a9aa2001a45e693db2cdbf69577094d3fe6597b564ad2d2202b65fba76134b - languageName: node - linkType: hard - "prebuild-install@npm:^7.1.1": version: 7.1.1 resolution: "prebuild-install@npm:7.1.1" @@ -15072,13 +11929,6 @@ __metadata: languageName: node linkType: hard -"precond@npm:0.2": - version: 0.2.3 - resolution: "precond@npm:0.2.3" - checksum: c613e7d68af3e0b43a294a994bf067cc2bc44b03fd17bc4fb133e30617a4f5b49414b08e9b392d52d7c6822d8a71f66a7fe93a8a1e7d02240177202cff3f63ef - languageName: node - linkType: hard - "prelude-ls@npm:^1.2.1": version: 1.2.1 resolution: "prelude-ls@npm:1.2.1" @@ -15093,13 +11943,6 @@ __metadata: languageName: node linkType: hard -"prepend-http@npm:^2.0.0": - version: 2.0.0 - resolution: "prepend-http@npm:2.0.0" - checksum: 7694a9525405447662c1ffd352fcb41b6410c705b739b6f4e3a3e21cf5fdede8377890088e8934436b8b17ba55365a615f153960f30877bf0d0392f9e93503ea - languageName: node - linkType: hard - "prettier-linter-helpers@npm:^1.0.0": version: 1.0.0 resolution: "prettier-linter-helpers@npm:1.0.0" @@ -15109,19 +11952,24 @@ __metadata: languageName: node linkType: hard -"prettier-plugin-solidity@npm:^1.0.0-beta.19": - version: 1.0.0-dev.24 - resolution: "prettier-plugin-solidity@npm:1.0.0-dev.24" +"prettier-linter-helpers@npm:^1.0.1": + version: 1.0.1 + resolution: "prettier-linter-helpers@npm:1.0.1" dependencies: - "@solidity-parser/parser": ^0.14.3 - emoji-regex: ^10.1.0 - escape-string-regexp: ^4.0.0 - semver: ^7.3.7 - solidity-comments-extractor: ^0.0.7 - string-width: ^4.2.3 + fast-diff: ^1.1.2 + checksum: 2dc35f5036a35f4c4f5e645887edda1436acb63687a7f12b2383e0a6f3c1f76b8a0a4709fe4d82e19157210feb5984b159bb714d43290022911ab53d606474ec + languageName: node + linkType: hard + +"prettier-plugin-solidity@npm:^1.3.0": + version: 1.4.3 + resolution: "prettier-plugin-solidity@npm:1.4.3" + dependencies: + "@solidity-parser/parser": ^0.20.1 + semver: ^7.7.1 peerDependencies: - prettier: ^2.3.0 - checksum: 526bc7bfee1dde875bc9ac68e35f85578390ac69cac8180c6e522ed9df10775d8f4ec33440a5d267f69d55389aace9ff4c684eb1de637aabab8c3657a65e2324 + prettier: ">=2.3.0" + checksum: fe175497cff86fd5a7b5e31fac83111b4518d0bc98a2ca49dff42afa1ebb672ce7b23f28d40b0fbb7dda9851861cef9c4d68b94401b8a524f805c3b3319a4252 languageName: node linkType: hard @@ -15134,15 +11982,6 @@ __metadata: languageName: node linkType: hard -"prettier@npm:^2.1.2": - version: 2.7.1 - resolution: "prettier@npm:2.7.1" - bin: - prettier: bin-prettier.js - checksum: 55a4409182260866ab31284d929b3cb961e5fdb91fe0d2e099dac92eaecec890f36e524b4c19e6ceae839c99c6d7195817579cdffc8e2c80da0cb794463a748b - languageName: node - linkType: hard - "prettier@npm:^2.3.1": version: 2.8.3 resolution: "prettier@npm:2.8.3" @@ -15152,19 +11991,12 @@ __metadata: languageName: node linkType: hard -"prettier@npm:^2.4.1": - version: 2.4.1 - resolution: "prettier@npm:2.4.1" +"prettier@npm:^3.2.0": + version: 3.8.1 + resolution: "prettier@npm:3.8.1" bin: - prettier: bin-prettier.js - checksum: cc6830588b401b0d742862fe9c46bc9118204fb307c3abe0e49e95b35ed23629573807ffdf9cdd65289c252a0bb51fc0171437f6626ee36378dea80f0ee80b91 - languageName: node - linkType: hard - -"private@npm:^0.1.6, private@npm:^0.1.8": - version: 0.1.8 - resolution: "private@npm:0.1.8" - checksum: a00abd713d25389f6de7294f0e7879b8a5d09a9ec5fd81cc2f21b29d4f9a80ec53bc4222927d3a281d4aadd4cd373d9a28726fca3935921950dc75fd71d1fdbb + prettier: bin/prettier.cjs + checksum: 36fe4ecd95751aa17fea70b48afd5086e88002988238112fc1be30a5307af6983e1833be790b0cc1c54702b71f73b12bfec12c05166d7619e3151ab221654297 languageName: node linkType: hard @@ -15206,16 +12038,6 @@ __metadata: languageName: node linkType: hard -"promise-to-callback@npm:^1.0.0": - version: 1.0.0 - resolution: "promise-to-callback@npm:1.0.0" - dependencies: - is-fn: ^1.0.0 - set-immediate-shim: ^1.0.1 - checksum: 8c9e1327386e00f799589cdf96fff2586a13b52b0185222bc3199e1305ba9344589eedfd4038dcbaf5592d85d567097d1507b81e948b7fff6ffdd3de49d54e14 - languageName: node - linkType: hard - "promise@npm:^8.0.0": version: 8.1.0 resolution: "promise@npm:8.1.0" @@ -15287,20 +12109,6 @@ __metadata: languageName: node linkType: hard -"prr@npm:~1.0.1": - version: 1.0.1 - resolution: "prr@npm:1.0.1" - checksum: 3bca2db0479fd38f8c4c9439139b0c42dcaadcc2fbb7bb8e0e6afaa1383457f1d19aea9e5f961d5b080f1cfc05bfa1fe9e45c97a1d3fd6d421950a73d3108381 - languageName: node - linkType: hard - -"pseudomap@npm:^1.0.1": - version: 1.0.2 - resolution: "pseudomap@npm:1.0.2" - checksum: 856c0aae0ff2ad60881168334448e898ad7a0e45fe7386d114b150084254c01e200c957cf378378025df4e052c7890c5bd933939b0e0d2ecfcc1dc2f0b2991f5 - languageName: node - linkType: hard - "psl@npm:^1.1.28": version: 1.8.0 resolution: "psl@npm:1.8.0" @@ -15322,68 +12130,6 @@ __metadata: languageName: node linkType: hard -"pull-cat@npm:^1.1.9": - version: 1.1.11 - resolution: "pull-cat@npm:1.1.11" - checksum: 785173d94732ba5e6e65f27ee128542522aeb87519c5d72aa9b8bc510f6c4f67b91fcfd565782a20aafc116e57354f2dd0fa8fd039b45a61b8da89b0253a7440 - languageName: node - linkType: hard - -"pull-defer@npm:^0.2.2": - version: 0.2.3 - resolution: "pull-defer@npm:0.2.3" - checksum: 4ea99ed64a2d79167e87293aba5088cde91f210a319c690a65aa6704d829be33b76cecc732f8d4ed3eee47e7eb09a6f77042897ea6414862bacbd722ce182d66 - languageName: node - linkType: hard - -"pull-level@npm:^2.0.3": - version: 2.0.4 - resolution: "pull-level@npm:2.0.4" - dependencies: - level-post: ^1.0.7 - pull-cat: ^1.1.9 - pull-live: ^1.0.1 - pull-pushable: ^2.0.0 - pull-stream: ^3.4.0 - pull-window: ^2.1.4 - stream-to-pull-stream: ^1.7.1 - checksum: f4e0573b3ff3f3659eb50ac86b505aee12d5f4c1d8bafc3bf6fd67d173b3b39a3fe5161d8bfa5eba8a0c5873fbda75f3b160276cfa678d5edd517dcd3349ecc2 - languageName: node - linkType: hard - -"pull-live@npm:^1.0.1": - version: 1.0.1 - resolution: "pull-live@npm:1.0.1" - dependencies: - pull-cat: ^1.1.9 - pull-stream: ^3.4.0 - checksum: e4328771e811aec1e03996d1070ec8fecb2560cc48b96814cd9f4aebd870a710903f8693e423765d3d65d8021b3b9ccc38c8660baef3df45e217c9b1bbc5581a - languageName: node - linkType: hard - -"pull-pushable@npm:^2.0.0": - version: 2.2.0 - resolution: "pull-pushable@npm:2.2.0" - checksum: 1c88ef55f6f14799ae5cf060415d089d15452ef865d874f075c155f8224c321371cb7f04a10b3fba263b6f128158c78253efd18bcb54afbb99f9cae846f883a6 - languageName: node - linkType: hard - -"pull-stream@npm:^3.2.3, pull-stream@npm:^3.4.0, pull-stream@npm:^3.6.8": - version: 3.6.14 - resolution: "pull-stream@npm:3.6.14" - checksum: fc3d86d488894cdf1f980848886be54d8c9cf16a982e9f651098e673bf0134dd1be9b02435f59afe5b48d479c6bafb828348f7fac95fd4593633bffefdfb7503 - languageName: node - linkType: hard - -"pull-window@npm:^2.1.4": - version: 2.1.4 - resolution: "pull-window@npm:2.1.4" - dependencies: - looper: ^2.0.0 - checksum: e006995108a80c81eea93dfaadf68285dc5b9b3cbaf654da39731ca3f308376f15b0546c61730cd0fa38303e273a1845c6d65f0fda35ed9c66252a65e446df18 - languageName: node - linkType: hard - "pump@npm:^1.0.0": version: 1.0.3 resolution: "pump@npm:1.0.3" @@ -15404,13 +12150,6 @@ __metadata: languageName: node linkType: hard -"punycode@npm:1.3.2": - version: 1.3.2 - resolution: "punycode@npm:1.3.2" - checksum: b8807fd594b1db33335692d1f03e8beeddde6fda7fbb4a2e32925d88d20a3aa4cd8dcc0c109ccaccbd2ba761c208dfaaada83007087ea8bfb0129c9ef1b99ed6 - languageName: node - linkType: hard - "punycode@npm:2.1.0": version: 2.1.0 resolution: "punycode@npm:2.1.0" @@ -15502,14 +12241,7 @@ __metadata: languageName: node linkType: hard -"querystring@npm:0.2.0": - version: 0.2.0 - resolution: "querystring@npm:0.2.0" - checksum: 8258d6734f19be27e93f601758858c299bdebe71147909e367101ba459b95446fbe5b975bf9beb76390156a592b6f4ac3a68b6087cea165c259705b8b4e56a69 - languageName: node - linkType: hard - -"queue-microtask@npm:^1.2.2, queue-microtask@npm:^1.2.3": +"queue-microtask@npm:^1.2.2": version: 1.2.3 resolution: "queue-microtask@npm:1.2.3" checksum: b676f8c040cdc5b12723ad2f91414d267605b26419d5c821ff03befa817ddd10e238d22b25d604920340fd73efd8ba795465a0377c4adf45a4a41e4234e42dc4 @@ -15523,7 +12255,7 @@ __metadata: languageName: node linkType: hard -"randombytes@npm:^2.0.0, randombytes@npm:^2.0.1, randombytes@npm:^2.0.5, randombytes@npm:^2.0.6, randombytes@npm:^2.1.0": +"randombytes@npm:^2.0.0, randombytes@npm:^2.0.1, randombytes@npm:^2.0.5, randombytes@npm:^2.1.0": version: 2.1.0 resolution: "randombytes@npm:2.1.0" dependencies: @@ -15628,40 +12360,7 @@ __metadata: languageName: node linkType: hard -"read-pkg-up@npm:^1.0.1": - version: 1.0.1 - resolution: "read-pkg-up@npm:1.0.1" - dependencies: - find-up: ^1.0.0 - read-pkg: ^1.0.0 - checksum: d18399a0f46e2da32beb2f041edd0cda49d2f2cc30195a05c759ef3ed9b5e6e19ba1ad1bae2362bdec8c6a9f2c3d18f4d5e8c369e808b03d498d5781cb9122c7 - languageName: node - linkType: hard - -"read-pkg@npm:^1.0.0": - version: 1.1.0 - resolution: "read-pkg@npm:1.1.0" - dependencies: - load-json-file: ^1.0.0 - normalize-package-data: ^2.3.2 - path-type: ^1.0.0 - checksum: a0f5d5e32227ec8e6a028dd5c5134eab229768dcb7a5d9a41a284ed28ad4b9284fecc47383dc1593b5694f4de603a7ffaee84b738956b9b77e0999567485a366 - languageName: node - linkType: hard - -"readable-stream@npm:^1.0.33": - version: 1.1.14 - resolution: "readable-stream@npm:1.1.14" - dependencies: - core-util-is: ~1.0.0 - inherits: ~2.0.1 - isarray: 0.0.1 - string_decoder: ~0.10.x - checksum: 17dfeae3e909945a4a1abc5613ea92d03269ef54c49288599507fc98ff4615988a1c39a999dcf9aacba70233d9b7040bc11a5f2bfc947e262dedcc0a8b32b5a0 - languageName: node - linkType: hard - -"readable-stream@npm:^2.0.0, readable-stream@npm:^2.0.5, readable-stream@npm:^2.0.6, readable-stream@npm:^2.2.2, readable-stream@npm:^2.2.8, readable-stream@npm:^2.2.9, readable-stream@npm:^2.3.0, readable-stream@npm:^2.3.5, readable-stream@npm:^2.3.6, readable-stream@npm:~2.3.6": +"readable-stream@npm:^2.0.6, readable-stream@npm:^2.2.2, readable-stream@npm:^2.3.0, readable-stream@npm:^2.3.5": version: 2.3.7 resolution: "readable-stream@npm:2.3.7" dependencies: @@ -15676,29 +12375,29 @@ __metadata: languageName: node linkType: hard -"readable-stream@npm:^3.0.6, readable-stream@npm:^3.1.0, readable-stream@npm:^3.4.0, readable-stream@npm:^3.6.0": - version: 3.6.0 - resolution: "readable-stream@npm:3.6.0" +"readable-stream@npm:^3.1.1": + version: 3.6.2 + resolution: "readable-stream@npm:3.6.2" dependencies: inherits: ^2.0.3 string_decoder: ^1.1.1 util-deprecate: ^1.0.1 - checksum: d4ea81502d3799439bb955a3a5d1d808592cf3133350ed352aeaa499647858b27b1c4013984900238b0873ec8d0d8defce72469fb7a83e61d53f5ad61cb80dc8 + checksum: bdcbe6c22e846b6af075e32cf8f4751c2576238c5043169a1c221c92ee2878458a816a4ea33f4c67623c0b6827c8a400409bfb3cf0bf3381392d0b1dfb52ac8d languageName: node linkType: hard -"readable-stream@npm:^3.1.1": - version: 3.6.2 - resolution: "readable-stream@npm:3.6.2" +"readable-stream@npm:^3.4.0, readable-stream@npm:^3.6.0": + version: 3.6.0 + resolution: "readable-stream@npm:3.6.0" dependencies: inherits: ^2.0.3 string_decoder: ^1.1.1 util-deprecate: ^1.0.1 - checksum: bdcbe6c22e846b6af075e32cf8f4751c2576238c5043169a1c221c92ee2878458a816a4ea33f4c67623c0b6827c8a400409bfb3cf0bf3381392d0b1dfb52ac8d + checksum: d4ea81502d3799439bb955a3a5d1d808592cf3133350ed352aeaa499647858b27b1c4013984900238b0873ec8d0d8defce72469fb7a83e61d53f5ad61cb80dc8 languageName: node linkType: hard -"readable-stream@npm:~1.0.15, readable-stream@npm:~1.0.26-4": +"readable-stream@npm:~1.0.26-4": version: 1.0.34 resolution: "readable-stream@npm:1.0.34" dependencies: @@ -15710,6 +12409,13 @@ __metadata: languageName: node linkType: hard +"readdirp@npm:^4.0.1": + version: 4.1.2 + resolution: "readdirp@npm:4.1.2" + checksum: 3242ee125422cb7c0e12d51452e993f507e6ed3d8c490bc8bf3366c5cdd09167562224e429b13e9cb2b98d4b8b2b11dc100d3c73883aa92d657ade5a21ded004 + languageName: node + linkType: hard + "readdirp@npm:~3.2.0": version: 3.2.0 resolution: "readdirp@npm:3.2.0" @@ -15789,13 +12495,6 @@ __metadata: languageName: node linkType: hard -"regenerate@npm:^1.2.1": - version: 1.4.2 - resolution: "regenerate@npm:1.4.2" - checksum: 3317a09b2f802da8db09aa276e469b57a6c0dd818347e05b8862959c6193408242f150db5de83c12c3fa99091ad95fb42a6db2c3329bfaa12a0ea4cbbeb30cb0 - languageName: node - linkType: hard - "regenerator-runtime@npm:^0.10.5": version: 0.10.5 resolution: "regenerator-runtime@npm:0.10.5" @@ -15810,28 +12509,7 @@ __metadata: languageName: node linkType: hard -"regenerator-transform@npm:^0.10.0": - version: 0.10.1 - resolution: "regenerator-transform@npm:0.10.1" - dependencies: - babel-runtime: ^6.18.0 - babel-types: ^6.19.0 - private: ^0.1.6 - checksum: bd366a3b0fa0d0975c48fb9eff250363a9ab28c25b472ecdc397bb19a836746640a30d8f641718a895f9178564bd8a01a0179a9c8e5813f76fc29e62a115d9d7 - languageName: node - linkType: hard - -"regex-not@npm:^1.0.0, regex-not@npm:^1.0.2": - version: 1.0.2 - resolution: "regex-not@npm:1.0.2" - dependencies: - extend-shallow: ^3.0.2 - safe-regex: ^1.1.0 - checksum: 3081403de79559387a35ef9d033740e41818a559512668cef3d12da4e8a29ef34ee13c8ed1256b07e27ae392790172e8a15c8a06b72962fd4550476cde3d8f77 - languageName: node - linkType: hard - -"regexp.prototype.flags@npm:^1.2.0, regexp.prototype.flags@npm:^1.4.3": +"regexp.prototype.flags@npm:^1.4.3": version: 1.4.3 resolution: "regexp.prototype.flags@npm:1.4.3" dependencies: @@ -15860,65 +12538,13 @@ __metadata: languageName: node linkType: hard -"regexpp@npm:^3.0.0, regexpp@npm:^3.1.0, regexpp@npm:^3.2.0": +"regexpp@npm:^3.0.0": version: 3.2.0 resolution: "regexpp@npm:3.2.0" checksum: a78dc5c7158ad9ddcfe01aa9144f46e192ddbfa7b263895a70a5c6c73edd9ce85faf7c0430e59ac38839e1734e275b9c3de5c57ee3ab6edc0e0b1bdebefccef8 languageName: node linkType: hard -"regexpu-core@npm:^2.0.0": - version: 2.0.0 - resolution: "regexpu-core@npm:2.0.0" - dependencies: - regenerate: ^1.2.1 - regjsgen: ^0.2.0 - regjsparser: ^0.1.4 - checksum: 14a78eb4608fa991ded6a1433ee6a570f95a4cfb7fe312145a44d6ecbb3dc8c707016a099494c741aa0ac75a1329b40814d30ff134c0d67679c80187029c7d2d - languageName: node - linkType: hard - -"regjsgen@npm:^0.2.0": - version: 0.2.0 - resolution: "regjsgen@npm:0.2.0" - checksum: 1f3ae570151e2c29193cdc5a5890c0b83cd8c5029ed69315b0ea303bc2644f9ab5d536d2288fd9b70293fd351d7dd7fc1fc99ebe24554015c894dbce883bcf2b - languageName: node - linkType: hard - -"regjsparser@npm:^0.1.4": - version: 0.1.5 - resolution: "regjsparser@npm:0.1.5" - dependencies: - jsesc: ~0.5.0 - bin: - regjsparser: bin/parser - checksum: 1feba2f3f2d4f1ef9f5f4e0f20c827cf866d4f65c51502eb64db4d4dd9c656f8c70f6c79537c892bf0fc9592c96f732519f7d8ad4a82f3b622756118ac737970 - languageName: node - linkType: hard - -"repeat-element@npm:^1.1.2": - version: 1.1.4 - resolution: "repeat-element@npm:1.1.4" - checksum: 1edd0301b7edad71808baad226f0890ba709443f03a698224c9ee4f2494c317892dc5211b2ba8cbea7194a9ddbcac01e283bd66de0467ab24ee1fc1a3711d8a9 - languageName: node - linkType: hard - -"repeat-string@npm:^1.6.1": - version: 1.6.1 - resolution: "repeat-string@npm:1.6.1" - checksum: 1b809fc6db97decdc68f5b12c4d1a671c8e3f65ec4a40c238bc5200e44e85bcc52a54f78268ab9c29fcf5fe4f1343e805420056d1f30fa9a9ee4c2d93e3cc6c0 - languageName: node - linkType: hard - -"repeating@npm:^2.0.0": - version: 2.0.1 - resolution: "repeating@npm:2.0.1" - dependencies: - is-finite: ^1.0.0 - checksum: d2db0b69c5cb0c14dd750036e0abcd6b3c3f7b2da3ee179786b755cf737ca15fa0fff417ca72de33d6966056f4695440e680a352401fc02c95ade59899afbdd0 - languageName: node - linkType: hard - "req-cwd@npm:^2.0.0": version: 2.0.0 resolution: "req-cwd@npm:2.0.0" @@ -15961,7 +12587,7 @@ __metadata: languageName: node linkType: hard -"request@npm:2.88.2, request@npm:^2.79.0, request@npm:^2.85.0, request@npm:^2.88.0, request@npm:^2.88.2": +"request@npm:2.88.2, request@npm:^2.79.0, request@npm:^2.88.0, request@npm:^2.88.2": version: 2.88.2 resolution: "request@npm:2.88.2" dependencies: @@ -15996,27 +12622,13 @@ __metadata: languageName: node linkType: hard -"require-from-string@npm:^1.1.0": - version: 1.2.1 - resolution: "require-from-string@npm:1.2.1" - checksum: d2e0b0c798fe45d86456a32425635bd9d2a75a20e87f67294fa5cce5ed61fdf41e0c7c57afa981fb836299bfb0c37c915adb4d22478dc8d12edbf80a304e9324 - languageName: node - linkType: hard - -"require-from-string@npm:^2.0.0, require-from-string@npm:^2.0.2": +"require-from-string@npm:^2.0.2": version: 2.0.2 resolution: "require-from-string@npm:2.0.2" checksum: a03ef6895445f33a4015300c426699bc66b2b044ba7b670aa238610381b56d3f07c686251740d575e22f4c87531ba662d06937508f0f3c0f1ddc04db3130560b languageName: node linkType: hard -"require-main-filename@npm:^1.0.1": - version: 1.0.1 - resolution: "require-main-filename@npm:1.0.1" - checksum: 1fef30754da961f4e13c450c3eb60c7ae898a529c6ad6fa708a70bd2eed01564ceb299187b2899f5562804d797a059f39a5789884d0ac7b7ae1defc68fba4abf - languageName: node - linkType: hard - "require-main-filename@npm:^2.0.0": version: 2.0.0 resolution: "require-main-filename@npm:2.0.0" @@ -16045,13 +12657,6 @@ __metadata: languageName: node linkType: hard -"resolve-url@npm:^0.2.1": - version: 0.2.1 - resolution: "resolve-url@npm:0.2.1" - checksum: 7b7035b9ed6e7bc7d289e90aef1eab5a43834539695dac6416ca6e91f1a94132ae4796bbd173cdacfdc2ade90b5f38a3fb6186bebc1b221cd157777a23b9ad14 - languageName: node - linkType: hard - "resolve@^1.1.6, resolve@^1.20.0, resolve@npm:^1.10.1": version: 1.20.0 resolution: "resolve@npm:1.20.0" @@ -16078,19 +12683,6 @@ __metadata: languageName: node linkType: hard -"resolve@npm:^1.10.0, resolve@npm:^1.8.1, resolve@npm:~1.22.1": - version: 1.22.1 - resolution: "resolve@npm:1.22.1" - dependencies: - is-core-module: ^2.9.0 - path-parse: ^1.0.7 - supports-preserve-symlinks-flag: ^1.0.0 - bin: - resolve: bin/resolve - checksum: 07af5fc1e81aa1d866cbc9e9460fbb67318a10fa3c4deadc35c3ad8a898ee9a71a86a65e4755ac3195e0ea0cfbe201eb323ebe655ce90526fd61917313a34e4e - languageName: node - linkType: hard - "resolve@patch:resolve@1.1.x#~builtin": version: 1.1.7 resolution: "resolve@patch:resolve@npm%3A1.1.7#~builtin::version=1.1.7&hash=3bafbf" @@ -16117,28 +12709,6 @@ __metadata: languageName: node linkType: hard -"resolve@patch:resolve@^1.10.0#~builtin, resolve@patch:resolve@^1.8.1#~builtin, resolve@patch:resolve@~1.22.1#~builtin": - version: 1.22.1 - resolution: "resolve@patch:resolve@npm%3A1.22.1#~builtin::version=1.22.1&hash=c3c19d" - dependencies: - is-core-module: ^2.9.0 - path-parse: ^1.0.7 - supports-preserve-symlinks-flag: ^1.0.0 - bin: - resolve: bin/resolve - checksum: 5656f4d0bedcf8eb52685c1abdf8fbe73a1603bb1160a24d716e27a57f6cecbe2432ff9c89c2bd57542c3a7b9d14b1882b73bfe2e9d7849c9a4c0b8b39f02b8b - languageName: node - linkType: hard - -"responselike@npm:^1.0.2": - version: 1.0.2 - resolution: "responselike@npm:1.0.2" - dependencies: - lowercase-keys: ^1.0.0 - checksum: 2e9e70f1dcca3da621a80ce71f2f9a9cad12c047145c6ece20df22f0743f051cf7c73505e109814915f23f9e34fb0d358e22827723ee3d56b623533cab8eafcd - languageName: node - linkType: hard - "responselike@npm:^2.0.0": version: 2.0.1 resolution: "responselike@npm:2.0.1" @@ -16178,22 +12748,6 @@ __metadata: languageName: node linkType: hard -"resumer@npm:~0.0.0": - version: 0.0.0 - resolution: "resumer@npm:0.0.0" - dependencies: - through: ~2.3.4 - checksum: 21b1c257aac24840643fae9bc99ca6447a71a0039e7c6dcf64d0ead447ce511eff158d529f1b6258ad12668e66ee3e49ff14932d2b88a3bd578f483e79708104 - languageName: node - linkType: hard - -"ret@npm:~0.1.10": - version: 0.1.15 - resolution: "ret@npm:0.1.15" - checksum: d76a9159eb8c946586567bd934358dfc08a36367b3257f7a3d7255fdd7b56597235af23c6afa0d7f0254159e8051f93c918809962ebd6df24ca2a83dbe4d4151 - languageName: node - linkType: hard - "retimer@npm:^3.0.0": version: 3.0.0 resolution: "retimer@npm:3.0.0" @@ -16240,7 +12794,7 @@ __metadata: languageName: node linkType: hard -"rimraf@npm:^2.2.8, rimraf@npm:^2.6.3": +"rimraf@npm:^2.6.3": version: 2.7.1 resolution: "rimraf@npm:2.7.1" dependencies: @@ -16272,7 +12826,7 @@ __metadata: languageName: node linkType: hard -"rlp@npm:^2.0.0, rlp@npm:^2.2.1, rlp@npm:^2.2.2, rlp@npm:^2.2.3, rlp@npm:^2.2.4, rlp@npm:^2.2.7": +"rlp@npm:^2.0.0, rlp@npm:^2.2.3, rlp@npm:^2.2.4, rlp@npm:^2.2.7": version: 2.2.7 resolution: "rlp@npm:2.2.7" dependencies: @@ -16299,15 +12853,6 @@ __metadata: languageName: node linkType: hard -"run-parallel-limit@npm:^1.1.0": - version: 1.1.0 - resolution: "run-parallel-limit@npm:1.1.0" - dependencies: - queue-microtask: ^1.2.2 - checksum: 672c3b87e7f939c684b9965222b361421db0930223ed1e43ebf0e7e48ccc1a022ea4de080bef4d5468434e2577c33b7681e3f03b7593fdc49ad250a55381123c - languageName: node - linkType: hard - "run-parallel@npm:^1.1.9": version: 1.2.0 resolution: "run-parallel@npm:1.2.0" @@ -16317,13 +12862,6 @@ __metadata: languageName: node linkType: hard -"rustbn.js@npm:~0.2.0": - version: 0.2.0 - resolution: "rustbn.js@npm:0.2.0" - checksum: 2148e7ba34e70682907ee29df4784639e6eb025481b2c91249403b7ec57181980161868d9aa24822a5075dd1bb5a180dfedc77309e5f0d27b6301f9b563af99a - languageName: node - linkType: hard - "rx-lite@npm:^3.1.2": version: 3.1.2 resolution: "rx-lite@npm:3.1.2" @@ -16375,15 +12913,6 @@ __metadata: languageName: node linkType: hard -"safe-event-emitter@npm:^1.0.1": - version: 1.0.1 - resolution: "safe-event-emitter@npm:1.0.1" - dependencies: - events: ^3.0.0 - checksum: 2a15094bd28b0966571693f219b5a846949ae24f7ba87c6024f0ed552bef63ebe72970a784b85b77b1f03f1c95e78fabe19306d44538dbc4a3a685bed31c18c4 - languageName: node - linkType: hard - "safe-regex-test@npm:^1.0.0": version: 1.0.0 resolution: "safe-regex-test@npm:1.0.0" @@ -16395,15 +12924,6 @@ __metadata: languageName: node linkType: hard -"safe-regex@npm:^1.1.0": - version: 1.1.0 - resolution: "safe-regex@npm:1.1.0" - dependencies: - ret: ~0.1.10 - checksum: 9a8bba57c87a841f7997b3b951e8e403b1128c1a4fd1182f40cc1a20e2d490593d7c2a21030fadfea320c8e859219019e136f678c6689ed5960b391b822f01d5 - languageName: node - linkType: hard - "safer-buffer@npm:>= 2.1.2 < 3, safer-buffer@npm:>= 2.1.2 < 3.0.0, safer-buffer@npm:^2.0.2, safer-buffer@npm:^2.1.0, safer-buffer@npm:~2.1.0": version: 2.1.2 resolution: "safer-buffer@npm:2.1.2" @@ -16468,15 +12988,6 @@ __metadata: languageName: node linkType: hard -"scryptsy@npm:^1.2.1": - version: 1.2.1 - resolution: "scryptsy@npm:1.2.1" - dependencies: - pbkdf2: ^3.0.3 - checksum: e09cf253b0974171bbcb77fa46405bb07cb8e241e2851fc5f23b38526a33105f0f7748a4d60027642f40bd4518ada30b1dce5005c05d17a25cbcefad371d4259 - languageName: node - linkType: hard - "secp256k1@npm:^4.0.1": version: 4.0.2 resolution: "secp256k1@npm:4.0.2" @@ -16489,37 +13000,7 @@ __metadata: languageName: node linkType: hard -"seedrandom@npm:3.0.1": - version: 3.0.1 - resolution: "seedrandom@npm:3.0.1" - checksum: a8f5bd0e918c4d4b59afd6f5dbd28f5ab8d5f118ee59892c3712f581de51574ac6622aa38fa2d03476b661f8407e98d6ff32af3d7cfdb02c90d046e7f5f91952 - languageName: node - linkType: hard - -"semaphore-async-await@npm:^1.5.1": - version: 1.5.1 - resolution: "semaphore-async-await@npm:1.5.1" - checksum: 2dedf7c59ba5f2da860fed95a81017189de6257cbe06c9de0ff2e610a3ae427e9bde1ab7685a62b03ebc28982dee437110492215d75fd6dc8257ce7a38e66b74 - languageName: node - linkType: hard - -"semaphore@npm:>=1.0.1, semaphore@npm:^1.0.3, semaphore@npm:^1.1.0": - version: 1.1.0 - resolution: "semaphore@npm:1.1.0" - checksum: d2445d232ad9959048d4748ef54eb01bc7b60436be2b42fb7de20c4cffacf70eafeeecd3772c1baf408cfdce3805fa6618a4389590335671f18cde54ef3cfae4 - languageName: node - linkType: hard - -"semver@npm:2 || 3 || 4 || 5, semver@npm:^5.3.0, semver@npm:^5.5.0, semver@npm:^5.5.1, semver@npm:^5.6.0, semver@npm:^5.7.0": - version: 5.7.1 - resolution: "semver@npm:5.7.1" - bin: - semver: ./bin/semver - checksum: 57fd0acfd0bac382ee87cd52cd0aaa5af086a7dc8d60379dfe65fea491fb2489b6016400813930ecd61fd0952dae75c115287a1b16c234b1550887117744dfaf - languageName: node - linkType: hard - -"semver@npm:7.3.5, semver@npm:^7.2.1, semver@npm:^7.3.5": +"semver@npm:7.3.5, semver@npm:^7.3.5": version: 7.3.5 resolution: "semver@npm:7.3.5" dependencies: @@ -16541,6 +13022,15 @@ __metadata: languageName: node linkType: hard +"semver@npm:^5.5.0, semver@npm:^5.5.1, semver@npm:^5.7.0": + version: 5.7.1 + resolution: "semver@npm:5.7.1" + bin: + semver: ./bin/semver + checksum: 57fd0acfd0bac382ee87cd52cd0aaa5af086a7dc8d60379dfe65fea491fb2489b6016400813930ecd61fd0952dae75c115287a1b16c234b1550887117744dfaf + languageName: node + linkType: hard + "semver@npm:^6.1.0, semver@npm:^6.3.0": version: 6.3.0 resolution: "semver@npm:6.3.0" @@ -16572,21 +13062,21 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.6.2, semver@npm:^7.7.1": - version: 7.7.2 - resolution: "semver@npm:7.7.2" +"semver@npm:^7.6.0": + version: 7.7.4 + resolution: "semver@npm:7.7.4" bin: semver: bin/semver.js - checksum: dd94ba8f1cbc903d8eeb4dd8bf19f46b3deb14262b6717d0de3c804b594058ae785ef2e4b46c5c3b58733c99c83339068203002f9e37cfe44f7e2cc5e3d2f621 + checksum: 9b4a6a58e98b9723fafcafa393c9d4e8edefaa60b8dfbe39e30892a3604cf1f45f52df9cfb1ae1a22b44c8b3d57fec8a9bb7b3e1645431587cb272399ede152e languageName: node linkType: hard -"semver@npm:~5.4.1": - version: 5.4.1 - resolution: "semver@npm:5.4.1" +"semver@npm:^7.6.2, semver@npm:^7.7.1": + version: 7.7.2 + resolution: "semver@npm:7.7.2" bin: - semver: ./bin/semver - checksum: d4bf8cc6a95b065a545ab35082b6ac6c5f4ebe1e1c570f72c252afe9b7e622f2479fb2a5cef3e937d8807d37bfdad2d1feebcc8610e06f556e552c22cad070a2 + semver: bin/semver.js + checksum: dd94ba8f1cbc903d8eeb4dd8bf19f46b3deb14262b6717d0de3c804b594058ae785ef2e4b46c5c3b58733c99c83339068203002f9e37cfe44f7e2cc5e3d2f621 languageName: node linkType: hard @@ -16620,6 +13110,15 @@ __metadata: languageName: node linkType: hard +"serialize-javascript@npm:^6.0.2": + version: 6.0.2 + resolution: "serialize-javascript@npm:6.0.2" + dependencies: + randombytes: ^2.1.0 + checksum: c4839c6206c1d143c0f80763997a361310305751171dd95e4b57efee69b8f6edd8960a0b7fbfc45042aadff98b206d55428aee0dc276efe54f100899c7fa8ab7 + languageName: node + linkType: hard + "serve-static@npm:1.15.0": version: 1.15.0 resolution: "serve-static@npm:1.15.0" @@ -16663,25 +13162,6 @@ __metadata: languageName: node linkType: hard -"set-immediate-shim@npm:^1.0.1": - version: 1.0.1 - resolution: "set-immediate-shim@npm:1.0.1" - checksum: 5085c84039d1e5eee73d2bf48ce765fcec76159021d0cc7b40e23bcdf62cb6d450ffb781e3c62c1118425242c48eae96df712cba0a20a437e86b0d4a15d51a11 - languageName: node - linkType: hard - -"set-value@npm:^2.0.0, set-value@npm:^2.0.1": - version: 2.0.1 - resolution: "set-value@npm:2.0.1" - dependencies: - extend-shallow: ^2.0.1 - is-extendable: ^0.1.1 - is-plain-object: ^2.0.3 - split-string: ^3.0.1 - checksum: 09a4bc72c94641aeae950eb60dc2755943b863780fcc32e441eda964b64df5e3f50603d5ebdd33394ede722528bd55ed43aae26e9df469b4d32e2292b427b601 - languageName: node - linkType: hard - "setimmediate@npm:1.0.4": version: 1.0.4 resolution: "setimmediate@npm:1.0.4" @@ -16856,20 +13336,6 @@ __metadata: languageName: node linkType: hard -"slash@npm:^1.0.0": - version: 1.0.0 - resolution: "slash@npm:1.0.0" - checksum: 4b6e21b1fba6184a7e2efb1dd173f692d8a845584c1bbf9dc818ff86f5a52fc91b413008223d17cc684604ee8bb9263a420b1182027ad9762e35388434918860 - languageName: node - linkType: hard - -"slash@npm:^2.0.0": - version: 2.0.0 - resolution: "slash@npm:2.0.0" - checksum: 512d4350735375bd11647233cb0e2f93beca6f53441015eea241fe784d8068281c3987fbaa93e7ef1c38df68d9c60013045c92837423c69115297d6169aa85e6 - languageName: node - linkType: hard - "slash@npm:^3.0.0": version: 3.0.0 resolution: "slash@npm:3.0.0" @@ -16906,42 +13372,6 @@ __metadata: languageName: node linkType: hard -"snapdragon-node@npm:^2.0.1": - version: 2.1.1 - resolution: "snapdragon-node@npm:2.1.1" - dependencies: - define-property: ^1.0.0 - isobject: ^3.0.0 - snapdragon-util: ^3.0.1 - checksum: 9bb57d759f9e2a27935dbab0e4a790137adebace832b393e350a8bf5db461ee9206bb642d4fe47568ee0b44080479c8b4a9ad0ebe3712422d77edf9992a672fd - languageName: node - linkType: hard - -"snapdragon-util@npm:^3.0.1": - version: 3.0.1 - resolution: "snapdragon-util@npm:3.0.1" - dependencies: - kind-of: ^3.2.0 - checksum: 684997dbe37ec995c03fd3f412fba2b711fc34cb4010452b7eb668be72e8811a86a12938b511e8b19baf853b325178c56d8b78d655305e5cfb0bb8b21677e7b7 - languageName: node - linkType: hard - -"snapdragon@npm:^0.8.1": - version: 0.8.2 - resolution: "snapdragon@npm:0.8.2" - dependencies: - base: ^0.11.1 - debug: ^2.2.0 - define-property: ^0.2.5 - extend-shallow: ^2.0.1 - map-cache: ^0.2.2 - source-map: ^0.5.6 - source-map-resolve: ^0.5.0 - use: ^3.1.0 - checksum: a197f242a8f48b11036563065b2487e9b7068f50a20dd81d9161eca6af422174fc158b8beeadbe59ce5ef172aa5718143312b3aebaae551c124b7824387c8312 - languageName: node - linkType: hard - "socks-proxy-agent@npm:^6.0.0": version: 6.1.0 resolution: "socks-proxy-agent@npm:6.1.0" @@ -16963,55 +13393,20 @@ __metadata: languageName: node linkType: hard -"solc@npm:0.7.3": - version: 0.7.3 - resolution: "solc@npm:0.7.3" +"solc@npm:0.8.26": + version: 0.8.26 + resolution: "solc@npm:0.8.26" dependencies: command-exists: ^1.2.8 - commander: 3.0.2 + commander: ^8.1.0 follow-redirects: ^1.12.1 - fs-extra: ^0.30.0 - js-sha3: 0.8.0 - memorystream: ^0.3.1 - require-from-string: ^2.0.0 - semver: ^5.5.0 - tmp: 0.0.33 - bin: - solcjs: solcjs - checksum: 2d8eb16c6d8f648213c94dc8d977cffe5099cba7d41c82d92d769ef71ae8320a985065ce3d6c306440a85f8e8d2b27fb30bdd3ac38f69e5c1fa0ab8a3fb2f217 - languageName: node - linkType: hard - -"solc@npm:^0.4.20": - version: 0.4.26 - resolution: "solc@npm:0.4.26" - dependencies: - fs-extra: ^0.30.0 - memorystream: ^0.3.1 - require-from-string: ^1.1.0 - semver: ^5.3.0 - yargs: ^4.7.1 - bin: - solcjs: solcjs - checksum: 041da7ff725c19023ef34a17f83b3303971d2e62bcea9d0fd3c7af728d6f40ff7cdf2b806d0208a3336d3c9be18c321955e1712ab39ee57390ba00d512def946 - languageName: node - linkType: hard - -"solc@npm:^0.6.3": - version: 0.6.12 - resolution: "solc@npm:0.6.12" - dependencies: - command-exists: ^1.2.8 - commander: 3.0.2 - fs-extra: ^0.30.0 js-sha3: 0.8.0 memorystream: ^0.3.1 - require-from-string: ^2.0.0 semver: ^5.5.0 tmp: 0.0.33 bin: - solcjs: solcjs - checksum: 1e2bf927f3ef4f3b195b7619ff64f715916d94dc59091a8a710e47bdd4b18e0bd92b55ea43a04ce7fabce9ad7a3e4e73ccaf127a50ebbf963a9de9046576e3b6 + solcjs: solc.js + checksum: e3eaeac76e60676377b357af8f3919d4c8c6a74b74112b49279fe8c74a3dfa1de8afe4788689fc307453bde336edc8572988d2cf9e909f84d870420eb640400c languageName: node linkType: hard @@ -17081,38 +13476,34 @@ __metadata: languageName: node linkType: hard -"solidity-comments-extractor@npm:^0.0.7": - version: 0.0.7 - resolution: "solidity-comments-extractor@npm:0.0.7" - checksum: a5cedf2310709969bc1783a6c336171478536f2f0ea96ad88437e0ef1e8844c0b37dd75591b0a824ec9c30640ea7e31b5f03128e871e6235bef3426617ce96c4 - languageName: node - linkType: hard - -"solidity-coverage@npm:^0.7.17": - version: 0.7.22 - resolution: "solidity-coverage@npm:0.7.22" +"solidity-coverage@npm:^0.8.0": + version: 0.8.17 + resolution: "solidity-coverage@npm:0.8.17" dependencies: - "@solidity-parser/parser": ^0.14.0 - "@truffle/provider": ^0.2.24 + "@ethersproject/abi": ^5.0.9 + "@solidity-parser/parser": ^0.20.1 chalk: ^2.4.2 death: ^1.1.0 - detect-port: ^1.3.0 + difflib: ^0.2.4 fs-extra: ^8.1.0 ghost-testrpc: ^0.0.2 global-modules: ^2.0.0 globby: ^10.0.1 jsonschema: ^1.2.4 - lodash: ^4.17.15 + lodash: ^4.17.21 + mocha: ^10.2.0 node-emoji: ^1.10.0 pify: ^4.0.1 recursive-readdir: ^2.2.2 sc-istanbul: ^0.4.5 semver: ^7.3.4 shelljs: ^0.8.3 - web3-utils: ^1.3.0 + web3-utils: ^1.3.6 + peerDependencies: + hardhat: ^2.11.0 bin: solidity-coverage: plugins/bin.js - checksum: 875415450979068ed559011d13e6d52eb41b8239f650960e5f24fcd61f2509e60955de647663fba3df56a2321e6a6bbad32525cf868aaf37f0eff4774eeb4c32 + checksum: 84845b9935a2afb0070ffb209752786ddcf1c8198f4c6b6193a879a9c4dcc3c374703bc29cd0f4cad227463366cf7cf6b8017995f9f364fc545c496df14bf227 languageName: node linkType: hard @@ -17133,38 +13524,6 @@ __metadata: languageName: node linkType: hard -"source-map-resolve@npm:^0.5.0": - version: 0.5.3 - resolution: "source-map-resolve@npm:0.5.3" - dependencies: - atob: ^2.1.2 - decode-uri-component: ^0.2.0 - resolve-url: ^0.2.1 - source-map-url: ^0.4.0 - urix: ^0.1.0 - checksum: c73fa44ac00783f025f6ad9e038ab1a2e007cd6a6b86f47fe717c3d0765b4a08d264f6966f3bd7cd9dbcd69e4832783d5472e43247775b2a550d6f2155d24bae - languageName: node - linkType: hard - -"source-map-support@npm:0.5.12": - version: 0.5.12 - resolution: "source-map-support@npm:0.5.12" - dependencies: - buffer-from: ^1.0.0 - source-map: ^0.6.0 - checksum: abf93e6201f54bd5713d6f6d5aa32b3752d750ce3c68044733295622ea0c346177505a615e87c073a1e0ad9b1d17b87a58f81152a31d6459658e4e9c17132db6 - languageName: node - linkType: hard - -"source-map-support@npm:^0.4.15": - version: 0.4.18 - resolution: "source-map-support@npm:0.4.18" - dependencies: - source-map: ^0.5.6 - checksum: 669aa7e992fec586fac0ba9a8dea8ce81b7328f92806335f018ffac5709afb2920e3870b4e56c68164282607229f04b8bbcf5d0e5c845eb1b5119b092e7585c0 - languageName: node - linkType: hard - "source-map-support@npm:^0.5.13, source-map-support@npm:^0.5.16, source-map-support@npm:^0.5.20": version: 0.5.21 resolution: "source-map-support@npm:0.5.21" @@ -17175,20 +13534,6 @@ __metadata: languageName: node linkType: hard -"source-map-url@npm:^0.4.0": - version: 0.4.1 - resolution: "source-map-url@npm:0.4.1" - checksum: 64c5c2c77aff815a6e61a4120c309ae4cac01298d9bcbb3deb1b46a4dd4c46d4a1eaeda79ec9f684766ae80e8dc86367b89326ce9dd2b89947bd9291fc1ac08c - languageName: node - linkType: hard - -"source-map@npm:^0.5.6, source-map@npm:^0.5.7": - version: 0.5.7 - resolution: "source-map@npm:0.5.7" - checksum: 5dc2043b93d2f194142c7f38f74a24670cd7a0063acdaf4bf01d2964b402257ae843c2a8fa822ad5b71013b5fcafa55af7421383da919752f22ff488bc553f4d - languageName: node - linkType: hard - "source-map@npm:^0.6.0, source-map@npm:^0.6.1": version: 0.6.1 resolution: "source-map@npm:0.6.1" @@ -17205,40 +13550,6 @@ __metadata: languageName: node linkType: hard -"spdx-correct@npm:^3.0.0": - version: 3.1.1 - resolution: "spdx-correct@npm:3.1.1" - dependencies: - spdx-expression-parse: ^3.0.0 - spdx-license-ids: ^3.0.0 - checksum: 77ce438344a34f9930feffa61be0eddcda5b55fc592906ef75621d4b52c07400a97084d8701557b13f7d2aae0cb64f808431f469e566ef3fe0a3a131dcb775a6 - languageName: node - linkType: hard - -"spdx-exceptions@npm:^2.1.0": - version: 2.3.0 - resolution: "spdx-exceptions@npm:2.3.0" - checksum: cb69a26fa3b46305637123cd37c85f75610e8c477b6476fa7354eb67c08128d159f1d36715f19be6f9daf4b680337deb8c65acdcae7f2608ba51931540687ac0 - languageName: node - linkType: hard - -"spdx-expression-parse@npm:^3.0.0": - version: 3.0.1 - resolution: "spdx-expression-parse@npm:3.0.1" - dependencies: - spdx-exceptions: ^2.1.0 - spdx-license-ids: ^3.0.0 - checksum: a1c6e104a2cbada7a593eaa9f430bd5e148ef5290d4c0409899855ce8b1c39652bcc88a725259491a82601159d6dc790bedefc9016c7472f7de8de7361f8ccde - languageName: node - linkType: hard - -"spdx-license-ids@npm:^3.0.0": - version: 3.0.12 - resolution: "spdx-license-ids@npm:3.0.12" - checksum: 92a4dddce62ce1db6fe54a7a839cf85e06abc308fc83b776a55b44e4f1906f02e7ebd506120847039e976bbbad359ea8bdfafb7925eae5cd7e73255f02e0b7d6 - languageName: node - linkType: hard - "split-ca@npm:^1.0.0": version: 1.0.1 resolution: "split-ca@npm:1.0.1" @@ -17246,15 +13557,6 @@ __metadata: languageName: node linkType: hard -"split-string@npm:^3.0.1, split-string@npm:^3.0.2": - version: 3.1.0 - resolution: "split-string@npm:3.1.0" - dependencies: - extend-shallow: ^3.0.0 - checksum: ae5af5c91bdc3633628821bde92fdf9492fa0e8a63cf6a0376ed6afde93c701422a1610916f59be61972717070119e848d10dfbbd5024b7729d6a71972d2a84c - languageName: node - linkType: hard - "sprintf-js@npm:~1.0.2": version: 1.0.3 resolution: "sprintf-js@npm:1.0.3" @@ -17301,16 +13603,6 @@ __metadata: languageName: node linkType: hard -"static-extend@npm:^0.1.1": - version: 0.1.2 - resolution: "static-extend@npm:0.1.2" - dependencies: - define-property: ^0.2.5 - object-copy: ^0.1.0 - checksum: 8657485b831f79e388a437260baf22784540417a9b29e11572c87735df24c22b84eda42107403a64b30861b2faf13df9f7fc5525d51f9d1d2303aba5cbf4e12c - languageName: node - linkType: hard - "statuses@npm:2.0.1": version: 2.0.1 resolution: "statuses@npm:2.0.1" @@ -17334,16 +13626,6 @@ __metadata: languageName: node linkType: hard -"stream-to-pull-stream@npm:^1.7.1": - version: 1.7.3 - resolution: "stream-to-pull-stream@npm:1.7.3" - dependencies: - looper: ^3.0.0 - pull-stream: ^3.2.3 - checksum: 2b878e3b3d5f435802866bfec8897361b9de4ce69f77669da1103cfc45f54833e7c183922468f30c046d375a1642f5a4801a808a8da0d3927c5de41d42a59bc0 - languageName: node - linkType: hard - "streamsearch@npm:^1.1.0": version: 1.1.0 resolution: "streamsearch@npm:1.1.0" @@ -17376,7 +13658,7 @@ __metadata: languageName: node linkType: hard -"string-width@npm:^1.0.2 || 2 || 3 || 4, string-width@npm:^4.0.0, string-width@npm:^4.1.0, string-width@npm:^4.2.0, string-width@npm:^4.2.3": +"string-width@npm:^1.0.2 || 2 || 3 || 4, string-width@npm:^4.0.0, string-width@npm:^4.1.0, string-width@npm:^4.2.0, string-width@npm:^4.2.2, string-width@npm:^4.2.3": version: 4.2.3 resolution: "string-width@npm:4.2.3" dependencies: @@ -17419,17 +13701,6 @@ __metadata: languageName: node linkType: hard -"string.prototype.trim@npm:~1.2.6": - version: 1.2.6 - resolution: "string.prototype.trim@npm:1.2.6" - dependencies: - call-bind: ^1.0.2 - define-properties: ^1.1.4 - es-abstract: ^1.19.5 - checksum: c5968e023afa9dec6a669c1f427f59aeb74f6f7ee5b0f4b9f0ffcef1d3846aa78b02227448cc874bbfa25dd1f8fd2324041c6cade38d4a986e4ade121ce1ea79 - languageName: node - linkType: hard - "string.prototype.trimend@npm:^1.0.4": version: 1.0.4 resolution: "string.prototype.trimend@npm:1.0.4" @@ -17555,15 +13826,6 @@ __metadata: languageName: node linkType: hard -"strip-bom@npm:^2.0.0": - version: 2.0.0 - resolution: "strip-bom@npm:2.0.0" - dependencies: - is-utf8: ^0.2.0 - checksum: 08efb746bc67b10814cd03d79eb31bac633393a782e3f35efbc1b61b5165d3806d03332a97f362822cf0d4dd14ba2e12707fcff44fe1c870c48a063a0c9e4944 - languageName: node - linkType: hard - "strip-bom@npm:^3.0.0": version: 3.0.0 resolution: "strip-bom@npm:3.0.0" @@ -17571,13 +13833,6 @@ __metadata: languageName: node linkType: hard -"strip-eof@npm:^1.0.0": - version: 1.0.0 - resolution: "strip-eof@npm:1.0.0" - checksum: 40bc8ddd7e072f8ba0c2d6d05267b4e0a4800898c3435b5fb5f5a21e6e47dfaff18467e7aa0d1844bb5d6274c3097246595841fbfeb317e541974ee992cac506 - languageName: node - linkType: hard - "strip-final-newline@npm:^2.0.0": version: 2.0.0 resolution: "strip-final-newline@npm:2.0.0" @@ -17601,7 +13856,7 @@ __metadata: languageName: node linkType: hard -"strip-json-comments@npm:3.1.1, strip-json-comments@npm:^3.1.0, strip-json-comments@npm:^3.1.1": +"strip-json-comments@npm:3.1.1, strip-json-comments@npm:^3.1.1": version: 3.1.1 resolution: "strip-json-comments@npm:3.1.1" checksum: 492f73e27268f9b1c122733f28ecb0e7e8d8a531a6662efbd08e22cccb3f9475e90a1b82cab06a392f6afae6d2de636f977e231296400d0ec5304ba70f166443 @@ -17670,13 +13925,6 @@ __metadata: languageName: node linkType: hard -"supports-preserve-symlinks-flag@npm:^1.0.0": - version: 1.0.0 - resolution: "supports-preserve-symlinks-flag@npm:1.0.0" - checksum: 53b1e247e68e05db7b3808b99b892bd36fb096e6fba213a06da7fab22045e97597db425c724f2bbd6c99a3c295e1e73f3e4de78592289f38431049e1277ca0ae - languageName: node - linkType: hard - "swarm-js@npm:^0.1.40": version: 0.1.42 resolution: "swarm-js@npm:0.1.42" @@ -17716,6 +13964,15 @@ __metadata: languageName: node linkType: hard +"synckit@npm:^0.11.12": + version: 0.11.12 + resolution: "synckit@npm:0.11.12" + dependencies: + "@pkgr/core": ^0.2.9 + checksum: a53fb563d01ba8912a111b883fc3c701e267896ff8273e7aba9001f5f74711e125888f4039e93060795cd416122cf492ae419eb10a6a3e3b00e830917669d2cf + languageName: node + linkType: hard + "table-layout@npm:^1.0.2": version: 1.0.2 resolution: "table-layout@npm:1.0.2" @@ -17740,20 +13997,6 @@ __metadata: languageName: node linkType: hard -"table@npm:^6.0.9": - version: 6.7.2 - resolution: "table@npm:6.7.2" - dependencies: - ajv: ^8.0.1 - lodash.clonedeep: ^4.5.0 - lodash.truncate: ^4.4.2 - slice-ansi: ^4.0.0 - string-width: ^4.2.3 - strip-ansi: ^6.0.1 - checksum: d61f91d64b9be56ac66edd2a8c0f10fcc59995313f37198cb87de73a6b441a05ad36f4a567bd8736da35bc4a2f8f4049b0e4ff1d4356c0a7c2b91af48b8bf8b2 - languageName: node - linkType: hard - "table@npm:^6.8.0": version: 6.8.1 resolution: "table@npm:6.8.1" @@ -17767,31 +14010,6 @@ __metadata: languageName: node linkType: hard -"tape@npm:^4.6.3": - version: 4.16.1 - resolution: "tape@npm:4.16.1" - dependencies: - call-bind: ~1.0.2 - deep-equal: ~1.1.1 - defined: ~1.0.0 - dotignore: ~0.1.2 - for-each: ~0.3.3 - glob: ~7.2.3 - has: ~1.0.3 - inherits: ~2.0.4 - is-regex: ~1.1.4 - minimist: ~1.2.6 - object-inspect: ~1.12.2 - resolve: ~1.22.1 - resumer: ~0.0.0 - string.prototype.trim: ~1.2.6 - through: ~2.3.8 - bin: - tape: bin/tape - checksum: e60f5ca3b5915c1df7f019e16eb643c98a5f741be3823b1db8f6ccfdc8ec4de11d7fc612b3c5e263d222d79e050c39bb6a45ea82f9f82f3faa1db9c386ed67f2 - languageName: node - linkType: hard - "tar-fs@npm:^2.0.0": version: 2.1.1 resolution: "tar-fs@npm:2.1.1" @@ -17873,23 +14091,6 @@ __metadata: languageName: node linkType: hard -"test-value@npm:^2.1.0": - version: 2.1.0 - resolution: "test-value@npm:2.1.0" - dependencies: - array-back: ^1.0.3 - typical: ^2.6.0 - checksum: ce41ef4100c9ac84630e78d1ca06706714587faf255e44296ace1fc7bf5b888c160b8c0229d31467252a3b2b57197965194391f6ee0c54f33e0b8e3af3a33a0c - languageName: node - linkType: hard - -"testrpc@npm:0.0.1": - version: 0.0.1 - resolution: "testrpc@npm:0.0.1" - checksum: e27778552df2d0b938b062fdf41d44557f0eb3de75903cb90b87909f55a82a6345dd13e40d1498e718272b4e5225872dca66da73646c35df1031486bb0ed0fda - languageName: node - linkType: hard - "text-table@npm:^0.2.0": version: 0.2.0 resolution: "text-table@npm:0.2.0" @@ -17916,17 +14117,7 @@ __metadata: languageName: node linkType: hard -"through2@npm:^2.0.3": - version: 2.0.5 - resolution: "through2@npm:2.0.5" - dependencies: - readable-stream: ~2.3.6 - xtend: ~4.0.1 - checksum: beb0f338aa2931e5660ec7bf3ad949e6d2e068c31f4737b9525e5201b824ac40cac6a337224856b56bd1ddd866334bbfb92a9f57cd6f66bc3f18d3d86fc0fe50 - languageName: node - linkType: hard - -"through@npm:>=2.2.7 <3, through@npm:^2.3.6, through@npm:~2.3.4, through@npm:~2.3.8": +"through@npm:>=2.2.7 <3, through@npm:^2.3.6": version: 2.3.8 resolution: "through@npm:2.3.8" checksum: a38c3e059853c494af95d50c072b83f8b676a9ba2818dcc5b108ef252230735c54e0185437618596c790bbba8fcdaef5b290405981ffa09dce67b1f1bf190cbd @@ -17951,6 +14142,16 @@ __metadata: languageName: node linkType: hard +"tinyglobby@npm:^0.2.6": + version: 0.2.15 + resolution: "tinyglobby@npm:0.2.15" + dependencies: + fdir: ^6.5.0 + picomatch: ^4.0.3 + checksum: 0e33b8babff966c6ab86e9b825a350a6a98a63700fa0bb7ae6cf36a7770a508892383adc272f7f9d17aaf46a9d622b455e775b9949a3f951eaaf5dfb26331d44 + languageName: node + linkType: hard + "tmp-promise@npm:3.0.3": version: 3.0.3 resolution: "tmp-promise@npm:3.0.3" @@ -17969,15 +14170,6 @@ __metadata: languageName: node linkType: hard -"tmp@npm:0.1.0": - version: 0.1.0 - resolution: "tmp@npm:0.1.0" - dependencies: - rimraf: ^2.6.3 - checksum: 6bab8431de9d245d4264bd8cd6bb216f9d22f179f935dada92a11d1315572c8eb7c3334201e00594b4708608bd536fad3a63bfb037e7804d827d66aa53a1afcd - languageName: node - linkType: hard - "tmp@npm:^0.2.0": version: 0.2.1 resolution: "tmp@npm:0.2.1" @@ -17994,39 +14186,6 @@ __metadata: languageName: node linkType: hard -"to-fast-properties@npm:^1.0.3": - version: 1.0.3 - resolution: "to-fast-properties@npm:1.0.3" - checksum: bd0abb58c4722851df63419de3f6d901d5118f0440d3f71293ed776dd363f2657edaaf2dc470e3f6b7b48eb84aa411193b60db8a4a552adac30de9516c5cc580 - languageName: node - linkType: hard - -"to-object-path@npm:^0.3.0": - version: 0.3.0 - resolution: "to-object-path@npm:0.3.0" - dependencies: - kind-of: ^3.0.2 - checksum: 9425effee5b43e61d720940fa2b889623f77473d459c2ce3d4a580a4405df4403eec7be6b857455908070566352f9e2417304641ed158dda6f6a365fe3e66d70 - languageName: node - linkType: hard - -"to-readable-stream@npm:^1.0.0": - version: 1.0.0 - resolution: "to-readable-stream@npm:1.0.0" - checksum: 2bd7778490b6214a2c40276065dd88949f4cf7037ce3964c76838b8cb212893aeb9cceaaf4352a4c486e3336214c350270f3263e1ce7a0c38863a715a4d9aeb5 - languageName: node - linkType: hard - -"to-regex-range@npm:^2.1.0": - version: 2.1.1 - resolution: "to-regex-range@npm:2.1.1" - dependencies: - is-number: ^3.0.0 - repeat-string: ^1.6.1 - checksum: 46093cc14be2da905cc931e442d280b2e544e2bfdb9a24b3cf821be8d342f804785e5736c108d5be026021a05d7b38144980a61917eee3c88de0a5e710e10320 - languageName: node - linkType: hard - "to-regex-range@npm:^5.0.1": version: 5.0.1 resolution: "to-regex-range@npm:5.0.1" @@ -18036,18 +14195,6 @@ __metadata: languageName: node linkType: hard -"to-regex@npm:^3.0.1, to-regex@npm:^3.0.2": - version: 3.0.2 - resolution: "to-regex@npm:3.0.2" - dependencies: - define-property: ^2.0.2 - extend-shallow: ^3.0.2 - regex-not: ^1.0.2 - safe-regex: ^1.1.0 - checksum: 4ed4a619059b64e204aad84e4e5f3ea82d97410988bcece7cf6cbfdbf193d11bff48cf53842d88b8bb00b1bfc0d048f61f20f0709e6f393fd8fe0122662d9db4 - languageName: node - linkType: hard - "toidentifier@npm:1.0.1": version: 1.0.1 resolution: "toidentifier@npm:1.0.1" @@ -18072,10 +14219,12 @@ __metadata: languageName: node linkType: hard -"trim-right@npm:^1.0.1": - version: 1.0.1 - resolution: "trim-right@npm:1.0.1" - checksum: 9120af534e006a7424a4f9358710e6e707887b6ccf7ea69e50d6ac6464db1fe22268400def01752f09769025d480395159778153fb98d4a2f6f40d4cf5d4f3b6 +"ts-api-utils@npm:^1.3.0": + version: 1.4.3 + resolution: "ts-api-utils@npm:1.4.3" + peerDependencies: + typescript: ">=4.2.0" + checksum: ea00dee382d19066b2a3d8929f1089888b05fec797e32e7a7004938eda1dccf2e77274ee2afcd4166f53fab9b8d7ee90ebb225a3183f9ba8817d636f688a148d languageName: node linkType: hard @@ -18094,22 +14243,6 @@ __metadata: languageName: node linkType: hard -"ts-essentials@npm:^1.0.0": - version: 1.0.4 - resolution: "ts-essentials@npm:1.0.4" - checksum: 2e19bbe51203707ca732dcc6c3f238b2cf22bb9213d26ae0246c02325fb3e5f17c32505ac79c1bd538b7951a798155b07422e263a95cb295070a48233e45a1b5 - languageName: node - linkType: hard - -"ts-essentials@npm:^6.0.3": - version: 6.0.7 - resolution: "ts-essentials@npm:6.0.7" - peerDependencies: - typescript: ">=3.7.0" - checksum: b47a1793df9ea997d50d2cc9155433952b189cfca0c534a6f3f3dce6aa782a37574d2179dee6d55ed918835aa17addda49619ff2bd2eb3e60e331db3ce30a79b - languageName: node - linkType: hard - "ts-essentials@npm:^7.0.1": version: 7.0.3 resolution: "ts-essentials@npm:7.0.3" @@ -18119,25 +14252,6 @@ __metadata: languageName: node linkType: hard -"ts-generator@npm:^0.1.1": - version: 0.1.1 - resolution: "ts-generator@npm:0.1.1" - dependencies: - "@types/mkdirp": ^0.5.2 - "@types/prettier": ^2.1.1 - "@types/resolve": ^0.0.8 - chalk: ^2.4.1 - glob: ^7.1.2 - mkdirp: ^0.5.1 - prettier: ^2.1.2 - resolve: ^1.8.1 - ts-essentials: ^1.0.0 - bin: - ts-generator: dist/cli/run.js - checksum: 3add2e76afd7a4d9d9aee1ff26477ee4e8b4cc740b35787f9ea780c11aefc88e6c7833837eacc12b944c1883680639dc9cc47fe173eff95c62112f3a41132146 - languageName: node - linkType: hard - "ts-node@npm:^10.3.0, ts-node@npm:^10.9.1": version: 10.9.1 resolution: "ts-node@npm:10.9.1" @@ -18195,7 +14309,7 @@ __metadata: languageName: node linkType: hard -"tslib@npm:^1.11.1, tslib@npm:^1.8.1, tslib@npm:^1.9.0, tslib@npm:^1.9.3": +"tslib@npm:^1.11.1, tslib@npm:^1.9.0, tslib@npm:^1.9.3": version: 1.14.1 resolution: "tslib@npm:1.14.1" checksum: dbe628ef87f66691d5d2959b3e41b9ca0045c3ee3c7c7b906cc1e328b39f199bb1ad9e671c39025bd56122ac57dfbf7385a94843b1cc07c60a4db74795829acd @@ -18230,17 +14344,6 @@ __metadata: languageName: node linkType: hard -"tsutils@npm:^3.21.0": - version: 3.21.0 - resolution: "tsutils@npm:3.21.0" - dependencies: - tslib: ^1.8.1 - peerDependencies: - typescript: ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" - checksum: 1843f4c1b2e0f975e08c4c21caa4af4f7f65a12ac1b81b3b8489366826259323feb3fc7a243123453d2d1a02314205a7634e048d4a8009921da19f99755cdc48 - languageName: node - linkType: hard - "tunnel-agent@npm:^0.6.0": version: 0.6.0 resolution: "tunnel-agent@npm:0.6.0" @@ -18250,7 +14353,7 @@ __metadata: languageName: node linkType: hard -"tweetnacl-util@npm:^0.15.0, tweetnacl-util@npm:^0.15.1": +"tweetnacl-util@npm:^0.15.0": version: 0.15.1 resolution: "tweetnacl-util@npm:0.15.1" checksum: ae6aa8a52cdd21a95103a4cc10657d6a2040b36c7a6da7b9d3ab811c6750a2d5db77e8c36969e75fdee11f511aa2b91c552496c6e8e989b6e490e54aca2864fc @@ -18264,7 +14367,7 @@ __metadata: languageName: node linkType: hard -"tweetnacl@npm:^1.0.0, tweetnacl@npm:^1.0.3": +"tweetnacl@npm:^1.0.3": version: 1.0.3 resolution: "tweetnacl@npm:1.0.3" checksum: e4a57cac188f0c53f24c7a33279e223618a2bfb5fea426231991652a13247bea06b081fd745d71291fcae0f4428d29beba1b984b1f1ce6f66b06a6d1ab90645c @@ -18341,23 +14444,6 @@ __metadata: languageName: node linkType: hard -"typechain@npm:^3.0.0": - version: 3.0.0 - resolution: "typechain@npm:3.0.0" - dependencies: - command-line-args: ^4.0.7 - debug: ^4.1.1 - fs-extra: ^7.0.0 - js-sha3: ^0.8.0 - lodash: ^4.17.15 - ts-essentials: ^6.0.3 - ts-generator: ^0.1.1 - bin: - typechain: ./dist/cli/cli.js - checksum: a38aff5e89c41e20e2c3a1f7b5f04666dbc94b5592eba70ba7d1e0aeb49089d22ed3d35e55a0b0d1f0bfdcea9818157fa4ee3854ef818f46f6aa899520fe7c25 - languageName: node - linkType: hard - "typechain@npm:^8.1.1": version: 8.1.1 resolution: "typechain@npm:8.1.1" @@ -18443,73 +14529,23 @@ __metadata: languageName: node linkType: hard -"typescript@npm:^4.3.4": - version: 4.8.4 - resolution: "typescript@npm:4.8.4" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: 3e4f061658e0c8f36c820802fa809e0fd812b85687a9a2f5430bc3d0368e37d1c9605c3ce9b39df9a05af2ece67b1d844f9f6ea8ff42819f13bcb80f85629af0 - languageName: node - linkType: hard - -"typescript@npm:^4.9.4": - version: 4.9.4 - resolution: "typescript@npm:4.9.4" - bin: - tsc: bin/tsc - tsserver: bin/tsserver - checksum: e782fb9e0031cb258a80000f6c13530288c6d63f1177ed43f770533fdc15740d271554cdae86701c1dd2c83b082cea808b07e97fd68b38a172a83dbf9e0d0ef9 - languageName: node - linkType: hard - -"typescript@patch:typescript@^4.3.4#~builtin": - version: 4.8.4 - resolution: "typescript@patch:typescript@npm%3A4.8.4#~builtin::version=4.8.4&hash=1a91c8" +"typescript@npm:^5.4.0": + version: 5.9.3 + resolution: "typescript@npm:5.9.3" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: c981e82b77a5acdcc4e69af9c56cdecf5b934a87a08e7b52120596701e389a878b8e3f860e73ffb287bf649cc47a8c741262ce058148f71de4cdd88bb9c75153 + checksum: 0d0ffb84f2cd072c3e164c79a2e5a1a1f4f168e84cb2882ff8967b92afe1def6c2a91f6838fb58b168428f9458c57a2ba06a6737711fdd87a256bbe83e9a217f languageName: node linkType: hard -"typescript@patch:typescript@^4.9.4#~builtin": - version: 4.9.4 - resolution: "typescript@patch:typescript@npm%3A4.9.4#~builtin::version=4.9.4&hash=289587" +"typescript@patch:typescript@^5.4.0#~builtin": + version: 5.9.3 + resolution: "typescript@patch:typescript@npm%3A5.9.3#~builtin::version=5.9.3&hash=14eedb" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: 2160f7ad975c59b2f5816817d3916be1d156c5688a7517602b3b640c5015e740f4ba933996ac85371d68f7bbdd41602150fb8b68334122ac637fdb5418085e7a - languageName: node - linkType: hard - -"typewise-core@npm:^1.2, typewise-core@npm:^1.2.0": - version: 1.2.0 - resolution: "typewise-core@npm:1.2.0" - checksum: c21e83544546d1aba2f17377c25ae0eb571c2153b2e3705932515bef103dbe43e05d2286f238ad139341b1000da40583115a44cb5e69a2ef408572b13dab844b - languageName: node - linkType: hard - -"typewise@npm:^1.0.3": - version: 1.0.3 - resolution: "typewise@npm:1.0.3" - dependencies: - typewise-core: ^1.2.0 - checksum: eb3452b1387df8bf8e3b620720d240425a50ce402d7c064c21ac4b5d88c551ee4d1f26cd649b8a17a6d06f7a3675733de841723f8e06bb3edabfeacc4924af4a - languageName: node - linkType: hard - -"typewiselite@npm:~1.0.0": - version: 1.0.0 - resolution: "typewiselite@npm:1.0.0" - checksum: 2e13a652c041680e9e37501129715f97c2ff2b8f52b5e82acd9355c070ca7c126633ff96d2ad03945254c271c0d1cf9f4956090c93ad750717e00d100cbd0c87 - languageName: node - linkType: hard - -"typical@npm:^2.6.0, typical@npm:^2.6.1": - version: 2.6.1 - resolution: "typical@npm:2.6.1" - checksum: 6af04fefe50d90d3471f058b2cdc0f49b7436bdd605cd00acea7965926ff388a5a7d692ef144f45fccee6f8e896c065702ecc44b69057e2ce88c09e897c7d3a4 + checksum: 8bb8d86819ac86a498eada254cad7fb69c5f74778506c700c2a712daeaff21d3a6f51fd0d534fe16903cb010d1b74f89437a3d02d4d0ff5ca2ba9a4660de8497 languageName: node linkType: hard @@ -18576,10 +14612,10 @@ __metadata: languageName: node linkType: hard -"underscore@npm:1.9.1": - version: 1.9.1 - resolution: "underscore@npm:1.9.1" - checksum: bee6f587661a6a9ca2f77e611896141e0287af51d8ca6034b11d0d4163ddbdd181a9720078ddbe94d265b7694f4880bc7f4c2ad260cfb8985ee2f9adcf13df03 +"undici-types@npm:~6.21.0": + version: 6.21.0 + resolution: "undici-types@npm:6.21.0" + checksum: 46331c7d6016bf85b3e8f20c159d62f5ae471aba1eb3dc52fff35a0259d58dcc7d592d4cc4f00c5f9243fa738a11cfa48bd20203040d4a9e6bc25e807fab7ab3 languageName: node linkType: hard @@ -18599,18 +14635,6 @@ __metadata: languageName: node linkType: hard -"union-value@npm:^1.0.0": - version: 1.0.1 - resolution: "union-value@npm:1.0.1" - dependencies: - arr-union: ^3.1.0 - get-value: ^2.0.6 - is-extendable: ^0.1.1 - set-value: ^2.0.1 - checksum: a3464097d3f27f6aa90cf103ed9387541bccfc006517559381a10e0dffa62f465a9d9a09c9b9c3d26d0f4cbe61d4d010e2fbd710fd4bf1267a768ba8a774b0ba - languageName: node - linkType: hard - "unique-filename@npm:^1.1.1": version: 1.1.1 resolution: "unique-filename@npm:1.1.1" @@ -18643,13 +14667,6 @@ __metadata: languageName: node linkType: hard -"unorm@npm:^1.3.3": - version: 1.6.0 - resolution: "unorm@npm:1.6.0" - checksum: 9a86546256a45f855b6cfe719086785d6aada94f63778cecdecece8d814ac26af76cb6da70130da0a08b8803bbf0986e56c7ec4249038198f3de02607fffd811 - languageName: node - linkType: hard - "unpipe@npm:1.0.0, unpipe@npm:~1.0.0": version: 1.0.0 resolution: "unpipe@npm:1.0.0" @@ -18657,16 +14674,6 @@ __metadata: languageName: node linkType: hard -"unset-value@npm:^1.0.0": - version: 1.0.0 - resolution: "unset-value@npm:1.0.0" - dependencies: - has-value: ^0.3.1 - isobject: ^3.0.0 - checksum: 5990ecf660672be2781fc9fb322543c4aa592b68ed9a3312fa4df0e9ba709d42e823af090fc8f95775b4cd2c9a5169f7388f0cec39238b6d0d55a69fc2ab6b29 - languageName: node - linkType: hard - "untildify@npm:^4.0.0": version: 4.0.0 resolution: "untildify@npm:4.0.0" @@ -18683,22 +14690,6 @@ __metadata: languageName: node linkType: hard -"urix@npm:^0.1.0": - version: 0.1.0 - resolution: "urix@npm:0.1.0" - checksum: 4c076ecfbf3411e888547fe844e52378ab5ada2d2f27625139011eada79925e77f7fbf0e4016d45e6a9e9adb6b7e64981bd49b22700c7c401c5fc15f423303b3 - languageName: node - linkType: hard - -"url-parse-lax@npm:^3.0.0": - version: 3.0.0 - resolution: "url-parse-lax@npm:3.0.0" - dependencies: - prepend-http: ^2.0.0 - checksum: 1040e357750451173132228036aff1fd04abbd43eac1fb3e4fca7495a078bcb8d33cb765fe71ad7e473d9c94d98fd67adca63bd2716c815a2da066198dd37217 - languageName: node - linkType: hard - "url-set-query@npm:^1.0.0": version: 1.0.0 resolution: "url-set-query@npm:1.0.0" @@ -18706,16 +14697,6 @@ __metadata: languageName: node linkType: hard -"url@npm:^0.11.0": - version: 0.11.0 - resolution: "url@npm:0.11.0" - dependencies: - punycode: 1.3.2 - querystring: 0.2.0 - checksum: 50d100d3dd2d98b9fe3ada48cadb0b08aa6be6d3ac64112b867b56b19be4bfcba03c2a9a0d7922bfd7ac17d4834e88537749fe182430dfd9b68e520175900d90 - languageName: node - linkType: hard - "urlpattern-polyfill@npm:^8.0.0": version: 8.0.2 resolution: "urlpattern-polyfill@npm:8.0.2" @@ -18735,13 +14716,6 @@ __metadata: languageName: node linkType: hard -"use@npm:^3.1.0": - version: 3.1.1 - resolution: "use@npm:3.1.1" - checksum: 08a130289f5238fcbf8f59a18951286a6e660d17acccc9d58d9b69dfa0ee19aa038e8f95721b00b432c36d1629a9e32a464bf2e7e0ae6a244c42ddb30bdd8b33 - languageName: node - linkType: hard - "utf-8-validate@npm:^5.0.2": version: 5.0.10 resolution: "utf-8-validate@npm:5.0.10" @@ -18752,7 +14726,7 @@ __metadata: languageName: node linkType: hard -"utf8@npm:3.0.0, utf8@npm:^3.0.0": +"utf8@npm:3.0.0": version: 3.0.0 resolution: "utf8@npm:3.0.0" checksum: cb89a69ad9ab393e3eae9b25305b3ff08bebca9adc839191a34f90777eb2942f86a96369d2839925fea58f8f722f7e27031d697f10f5f39690f8c5047303e62d @@ -18766,19 +14740,6 @@ __metadata: languageName: node linkType: hard -"util.promisify@npm:^1.0.0": - version: 1.1.1 - resolution: "util.promisify@npm:1.1.1" - dependencies: - call-bind: ^1.0.0 - define-properties: ^1.1.3 - for-each: ^0.3.3 - has-symbols: ^1.0.1 - object.getownpropertydescriptors: ^2.1.1 - checksum: ea371c30b90576862487ae4efd7182aa5855019549a4019d82629acc2709e8ccb0f38944403eebec622fff8ebb44ac3f46a52d745d5f543d30606132a4905f96 - languageName: node - linkType: hard - "util@npm:^0.12.0": version: 0.12.5 resolution: "util@npm:0.12.5" @@ -18865,23 +14826,6 @@ __metadata: languageName: node linkType: hard -"v8-compile-cache@npm:^2.0.3": - version: 2.3.0 - resolution: "v8-compile-cache@npm:2.3.0" - checksum: adb0a271eaa2297f2f4c536acbfee872d0dd26ec2d76f66921aa7fc437319132773483344207bdbeee169225f4739016d8d2dbf0553913a52bb34da6d0334f8e - languageName: node - linkType: hard - -"validate-npm-package-license@npm:^3.0.1": - version: 3.0.4 - resolution: "validate-npm-package-license@npm:3.0.4" - dependencies: - spdx-correct: ^3.0.0 - spdx-expression-parse: ^3.0.0 - checksum: 35703ac889d419cf2aceef63daeadbe4e77227c39ab6287eeb6c1b36a746b364f50ba22e88591f5d017bc54685d8137bc2d328d0a896e4d3fd22093c0f32a9ad - languageName: node - linkType: hard - "varint@npm:^5.0.0": version: 5.0.2 resolution: "varint@npm:5.0.2" @@ -18986,29 +14930,6 @@ __metadata: languageName: node linkType: hard -"web3-bzz@npm:1.2.11": - version: 1.2.11 - resolution: "web3-bzz@npm:1.2.11" - dependencies: - "@types/node": ^12.12.6 - got: 9.6.0 - swarm-js: ^0.1.40 - underscore: 1.9.1 - checksum: 45136e7282819260357efdcdf6d81cb7b733b212aa1e46f1bbcaff70a33a2e3f6558936e6e1fc3bf75bb4c3220f844fc6b9d5bfaaa68a2f6ed0e8c0b02c97523 - languageName: node - linkType: hard - -"web3-bzz@npm:1.7.4": - version: 1.7.4 - resolution: "web3-bzz@npm:1.7.4" - dependencies: - "@types/node": ^12.12.6 - got: 9.6.0 - swarm-js: ^0.1.40 - checksum: 196a06ca913f093a53f1d78a77e702b8e227efbf6759be50d8ec1eb4161952902ebf9dd73a57c30ad7774cb4536c0cf3ec7c41c261f56e5813aa585a714d8dfc - languageName: node - linkType: hard - "web3-bzz@npm:1.8.0": version: 1.8.0 resolution: "web3-bzz@npm:1.8.0" @@ -19020,27 +14941,6 @@ __metadata: languageName: node linkType: hard -"web3-core-helpers@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core-helpers@npm:1.2.11" - dependencies: - underscore: 1.9.1 - web3-eth-iban: 1.2.11 - web3-utils: 1.2.11 - checksum: dac2ab85b8bec8251647d40f1dc5fcf30b2245de6d216328c51c9d619d12a567906c5bf8b542846552a56bf969edcfcb16fb67e3780461195df85cd506591f68 - languageName: node - linkType: hard - -"web3-core-helpers@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core-helpers@npm:1.7.4" - dependencies: - web3-eth-iban: 1.7.4 - web3-utils: 1.7.4 - checksum: 706b3617395a4cba1955e6d56f32cb65f645e0df854dd373263d61fd291fefaa6a490aeec94a4bebb45ed0aac3f044b783dfd35b77c74bb55eddc30f7c59b6a3 - languageName: node - linkType: hard - "web3-core-helpers@npm:1.8.0": version: 1.8.0 resolution: "web3-core-helpers@npm:1.8.0" @@ -19051,61 +14951,16 @@ __metadata: languageName: node linkType: hard -"web3-core-method@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core-method@npm:1.2.11" - dependencies: - "@ethersproject/transactions": ^5.0.0-beta.135 - underscore: 1.9.1 - web3-core-helpers: 1.2.11 - web3-core-promievent: 1.2.11 - web3-core-subscriptions: 1.2.11 - web3-utils: 1.2.11 - checksum: 7533c5b8c42df49969b9c95a2c9cb0abcd55a304ef4b276a5cc43673d27ffd9767a0caabe09271979b5afd0f788a51416f7018bc704d734ad78846c68dba15a7 - languageName: node - linkType: hard - -"web3-core-method@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core-method@npm:1.7.4" - dependencies: - "@ethersproject/transactions": ^5.6.2 - web3-core-helpers: 1.7.4 - web3-core-promievent: 1.7.4 - web3-core-subscriptions: 1.7.4 - web3-utils: 1.7.4 - checksum: 48b0dd9bfc936154228b6abbe9c795136c4a8350af281bb7b0f576fd8e5150a9fca79776b4bf4f53e3b2508f6df41f3230df97428894030f2e7bf5953cce93ce - languageName: node - linkType: hard - "web3-core-method@npm:1.8.0": version: 1.8.0 resolution: "web3-core-method@npm:1.8.0" dependencies: "@ethersproject/transactions": ^5.6.2 web3-core-helpers: 1.8.0 - web3-core-promievent: 1.8.0 - web3-core-subscriptions: 1.8.0 - web3-utils: 1.8.0 - checksum: 5b73af8a34c94cfaee8dd69435fe78cc6eccde2e30c2d9632b4efa96d18b8ee13012d14ed6cfe4350db6f9ea2e04c53e55a47ac31db013728812427828338290 - languageName: node - linkType: hard - -"web3-core-promievent@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core-promievent@npm:1.2.11" - dependencies: - eventemitter3: 4.0.4 - checksum: bd3661978f252ec0033881b32a5d4dec1bfeb7fb0f018d77c077c77b60c0f965215dcbd54c5fcbef739441dd7efbdbd6c9b20e275e05f5b4d2cee762937d95cc - languageName: node - linkType: hard - -"web3-core-promievent@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core-promievent@npm:1.7.4" - dependencies: - eventemitter3: 4.0.4 - checksum: 1d3b10f9ba51759548ff1d6988f663368a7ef1a207134651b9ee268d042d891b6307e7f6153230a122ad7533f3c8562298a46fe9479b74aac08bfaaf7ff2ec2f + web3-core-promievent: 1.8.0 + web3-core-subscriptions: 1.8.0 + web3-utils: 1.8.0 + checksum: 5b73af8a34c94cfaee8dd69435fe78cc6eccde2e30c2d9632b4efa96d18b8ee13012d14ed6cfe4350db6f9ea2e04c53e55a47ac31db013728812427828338290 languageName: node linkType: hard @@ -19118,32 +14973,6 @@ __metadata: languageName: node linkType: hard -"web3-core-requestmanager@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core-requestmanager@npm:1.2.11" - dependencies: - underscore: 1.9.1 - web3-core-helpers: 1.2.11 - web3-providers-http: 1.2.11 - web3-providers-ipc: 1.2.11 - web3-providers-ws: 1.2.11 - checksum: 84898bfec26319d06ccf7ae63821b7fbea8efc8a76015921530cc4eb85db39598c16598f1e51f95ed79146d7defafe7b924b5c6f6927fb2a153d01eb0862182c - languageName: node - linkType: hard - -"web3-core-requestmanager@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core-requestmanager@npm:1.7.4" - dependencies: - util: ^0.12.0 - web3-core-helpers: 1.7.4 - web3-providers-http: 1.7.4 - web3-providers-ipc: 1.7.4 - web3-providers-ws: 1.7.4 - checksum: 4e1decb11af99c46f1b73efc6a9204a9344444a5afe85f002c404e08522d4ab1dce9327a570e6e47911f257453c0a7663048b799875173d6f9f0eb3bcb782e30 - languageName: node - linkType: hard - "web3-core-requestmanager@npm:1.8.0": version: 1.8.0 resolution: "web3-core-requestmanager@npm:1.8.0" @@ -19157,27 +14986,6 @@ __metadata: languageName: node linkType: hard -"web3-core-subscriptions@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core-subscriptions@npm:1.2.11" - dependencies: - eventemitter3: 4.0.4 - underscore: 1.9.1 - web3-core-helpers: 1.2.11 - checksum: 7c8c07ea79fc9cf4ecb15ea37c5db38cc38e4b0545247d9ccc7ff6f4257565c03bcee569695a93abe02b8a98a6a9c227df880911ae324c0c6218a9571a3811f6 - languageName: node - linkType: hard - -"web3-core-subscriptions@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core-subscriptions@npm:1.7.4" - dependencies: - eventemitter3: 4.0.4 - web3-core-helpers: 1.7.4 - checksum: ff2cb87f676e9624fc92174193a073928029962816ba83282731e524e9a51d834fd55a27a3e94001a089486d09c9f9c23ac7d3c04b6da42c902017d53ba0bc4b - languageName: node - linkType: hard - "web3-core-subscriptions@npm:1.8.0": version: 1.8.0 resolution: "web3-core-subscriptions@npm:1.8.0" @@ -19188,36 +14996,6 @@ __metadata: languageName: node linkType: hard -"web3-core@npm:1.2.11": - version: 1.2.11 - resolution: "web3-core@npm:1.2.11" - dependencies: - "@types/bn.js": ^4.11.5 - "@types/node": ^12.12.6 - bignumber.js: ^9.0.0 - web3-core-helpers: 1.2.11 - web3-core-method: 1.2.11 - web3-core-requestmanager: 1.2.11 - web3-utils: 1.2.11 - checksum: 1793affddb4fa811f9781dc644b4017d95c6084a21bb866e0dc626f6d48bfc29eacf02237608b587ca49094e9342da878b64173510d99a6e9171f7a697e8cb36 - languageName: node - linkType: hard - -"web3-core@npm:1.7.4": - version: 1.7.4 - resolution: "web3-core@npm:1.7.4" - dependencies: - "@types/bn.js": ^5.1.0 - "@types/node": ^12.12.6 - bignumber.js: ^9.0.0 - web3-core-helpers: 1.7.4 - web3-core-method: 1.7.4 - web3-core-requestmanager: 1.7.4 - web3-utils: 1.7.4 - checksum: 9e797df444e782ccdc2230ec79ff8adbcfeabc27346c23cd034b43aa23435b005739dac0c4282db4f79271a03d5572e37490c888ca8d23cb5106b3e30d0c85c0 - languageName: node - linkType: hard - "web3-core@npm:1.8.0": version: 1.8.0 resolution: "web3-core@npm:1.8.0" @@ -19233,17 +15011,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-abi@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-abi@npm:1.2.11" - dependencies: - "@ethersproject/abi": 5.0.0-beta.153 - underscore: 1.9.1 - web3-utils: 1.2.11 - checksum: ef96c9c0faad2634d69f1c6dbf3414d0f292c0e534e477f47a1b14512c7099237a09d6b6ba91b624cea348e51e759106b128b0fe463d62f17f447e0a47071d76 - languageName: node - linkType: hard - "web3-eth-abi@npm:1.7.0": version: 1.7.0 resolution: "web3-eth-abi@npm:1.7.0" @@ -19254,16 +15021,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-abi@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-abi@npm:1.7.4" - dependencies: - "@ethersproject/abi": ^5.6.3 - web3-utils: 1.7.4 - checksum: f0ce4149dccf681349338d2ed5162d9f0fc4dcaf91639a4278cdec02e08858d969e56678cfc10f63668b7ddf41c53ff3d79d17fa92d158f96f94db3f31efb6f5 - languageName: node - linkType: hard - "web3-eth-abi@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-abi@npm:1.8.0" @@ -19274,44 +15031,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-accounts@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-accounts@npm:1.2.11" - dependencies: - crypto-browserify: 3.12.0 - eth-lib: 0.2.8 - ethereumjs-common: ^1.3.2 - ethereumjs-tx: ^2.1.1 - scrypt-js: ^3.0.1 - underscore: 1.9.1 - uuid: 3.3.2 - web3-core: 1.2.11 - web3-core-helpers: 1.2.11 - web3-core-method: 1.2.11 - web3-utils: 1.2.11 - checksum: 1653a7548337b538b280ced0d25dbf8b105954a5bf61726d5def25128ffc87c49d0d38b678a32e7d259e687f5e72cc452d92e14eaa8c9976a9153347e4afe7eb - languageName: node - linkType: hard - -"web3-eth-accounts@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-accounts@npm:1.7.4" - dependencies: - "@ethereumjs/common": ^2.5.0 - "@ethereumjs/tx": ^3.3.2 - crypto-browserify: 3.12.0 - eth-lib: 0.2.8 - ethereumjs-util: ^7.0.10 - scrypt-js: ^3.0.1 - uuid: 3.3.2 - web3-core: 1.7.4 - web3-core-helpers: 1.7.4 - web3-core-method: 1.7.4 - web3-utils: 1.7.4 - checksum: 565d57fc07ed057ab6ae94539ca57bd99fc1e95c5026d4cda561b73a7a77eb96a5f8b52683ffd351e7adba8b669c4988eb56f0f1f2f35ca1666f19dc83a7ed8b - languageName: node - linkType: hard - "web3-eth-accounts@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-accounts@npm:1.8.0" @@ -19331,39 +15050,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-contract@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-contract@npm:1.2.11" - dependencies: - "@types/bn.js": ^4.11.5 - underscore: 1.9.1 - web3-core: 1.2.11 - web3-core-helpers: 1.2.11 - web3-core-method: 1.2.11 - web3-core-promievent: 1.2.11 - web3-core-subscriptions: 1.2.11 - web3-eth-abi: 1.2.11 - web3-utils: 1.2.11 - checksum: 1dc74e11f09c895bd5b26c5dfb3a0818d6a38a573de9252a3a943acf6ba88a058313e2977c95564ab56c3696f1ca975237ae4f10c93d34d2978f11bb1119b4d7 - languageName: node - linkType: hard - -"web3-eth-contract@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-contract@npm:1.7.4" - dependencies: - "@types/bn.js": ^5.1.0 - web3-core: 1.7.4 - web3-core-helpers: 1.7.4 - web3-core-method: 1.7.4 - web3-core-promievent: 1.7.4 - web3-core-subscriptions: 1.7.4 - web3-eth-abi: 1.7.4 - web3-utils: 1.7.4 - checksum: bc420fd3e3fc571118774dbf2da82ca374be70595e85e3b515d8943a18bbd18ec1e945b2c872b1064ed593e8cc608e9168f227a25deb2dbf14779c93f6cf6329 - languageName: node - linkType: hard - "web3-eth-contract@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-contract@npm:1.8.0" @@ -19380,39 +15066,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-ens@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-ens@npm:1.2.11" - dependencies: - content-hash: ^2.5.2 - eth-ens-namehash: 2.0.8 - underscore: 1.9.1 - web3-core: 1.2.11 - web3-core-helpers: 1.2.11 - web3-core-promievent: 1.2.11 - web3-eth-abi: 1.2.11 - web3-eth-contract: 1.2.11 - web3-utils: 1.2.11 - checksum: 987999713c5c79f23a67ad244813212e9582566f6a7665312f887ce0eda77d91b85d3c0df21af14ef6ab6e970626d5d02129a2df3a8c257151f9540d6968a748 - languageName: node - linkType: hard - -"web3-eth-ens@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-ens@npm:1.7.4" - dependencies: - content-hash: ^2.5.2 - eth-ens-namehash: 2.0.8 - web3-core: 1.7.4 - web3-core-helpers: 1.7.4 - web3-core-promievent: 1.7.4 - web3-eth-abi: 1.7.4 - web3-eth-contract: 1.7.4 - web3-utils: 1.7.4 - checksum: d4352098ceb2ab6fda24789dc8377fcb13973fbcbc597b40365d6e3d3b8a2b74512cca6aa3710fa959af654fd989f40467ea6fa16e0d8c07421bba8bf090513b - languageName: node - linkType: hard - "web3-eth-ens@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-ens@npm:1.8.0" @@ -19429,26 +15082,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-iban@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-iban@npm:1.2.11" - dependencies: - bn.js: ^4.11.9 - web3-utils: 1.2.11 - checksum: 1c28b3ad2cad2af0a76b051fe2c05ed933476eaa99f2c245862f66d4e3d56e60ad26cf55120513f78648ab1ff2b8a6b751e63448cdb01b53b542334bf148286f - languageName: node - linkType: hard - -"web3-eth-iban@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-iban@npm:1.7.4" - dependencies: - bn.js: ^5.2.1 - web3-utils: 1.7.4 - checksum: 81a3c39baed3ff6efa034fe4f2a2f2932213cffa69084c45eb9b7ea2e4c7b902577f9c220ef4d1bbaa2907a5a436f3d723363af13edac62ac5312ba8c7c123b1 - languageName: node - linkType: hard - "web3-eth-iban@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-iban@npm:1.8.0" @@ -19459,34 +15092,6 @@ __metadata: languageName: node linkType: hard -"web3-eth-personal@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth-personal@npm:1.2.11" - dependencies: - "@types/node": ^12.12.6 - web3-core: 1.2.11 - web3-core-helpers: 1.2.11 - web3-core-method: 1.2.11 - web3-net: 1.2.11 - web3-utils: 1.2.11 - checksum: a754a16aaed1e97baf963f594b69c83bc4c1cf3f5b181b18720ce292583b4a1b70c7a5c22433679c3e66166773bb43731535d085db3bcfc72af48290553f5122 - languageName: node - linkType: hard - -"web3-eth-personal@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth-personal@npm:1.7.4" - dependencies: - "@types/node": ^12.12.6 - web3-core: 1.7.4 - web3-core-helpers: 1.7.4 - web3-core-method: 1.7.4 - web3-net: 1.7.4 - web3-utils: 1.7.4 - checksum: 9e57f5e7d878d6d7c9ff671062d7dd18ac8fe91467d1880b842e257d9578888daa831dcdc5b798eed3299eb50c3bc6c24db2f630d40e63eed05382370d3f6933 - languageName: node - linkType: hard - "web3-eth-personal@npm:1.8.0": version: 1.8.0 resolution: "web3-eth-personal@npm:1.8.0" @@ -19501,47 +15106,6 @@ __metadata: languageName: node linkType: hard -"web3-eth@npm:1.2.11": - version: 1.2.11 - resolution: "web3-eth@npm:1.2.11" - dependencies: - underscore: 1.9.1 - web3-core: 1.2.11 - web3-core-helpers: 1.2.11 - web3-core-method: 1.2.11 - web3-core-subscriptions: 1.2.11 - web3-eth-abi: 1.2.11 - web3-eth-accounts: 1.2.11 - web3-eth-contract: 1.2.11 - web3-eth-ens: 1.2.11 - web3-eth-iban: 1.2.11 - web3-eth-personal: 1.2.11 - web3-net: 1.2.11 - web3-utils: 1.2.11 - checksum: eaf361bc59859e7e9078e57f438564f10ea5c0cc00404d3ccf537f3c8d11d963b74f8c3981f4160f1ed2e3c4d9d97a5ff85b33744d5083afde8dfd5dde887034 - languageName: node - linkType: hard - -"web3-eth@npm:1.7.4": - version: 1.7.4 - resolution: "web3-eth@npm:1.7.4" - dependencies: - web3-core: 1.7.4 - web3-core-helpers: 1.7.4 - web3-core-method: 1.7.4 - web3-core-subscriptions: 1.7.4 - web3-eth-abi: 1.7.4 - web3-eth-accounts: 1.7.4 - web3-eth-contract: 1.7.4 - web3-eth-ens: 1.7.4 - web3-eth-iban: 1.7.4 - web3-eth-personal: 1.7.4 - web3-net: 1.7.4 - web3-utils: 1.7.4 - checksum: 09a016cd76b87edd45f4f3c1e31589da6a9753383f366d205078ba7c5455bf520daf6905e701f66c69afc145ded59af4e388d72b41a9679085963d625adf85ae - languageName: node - linkType: hard - "web3-eth@npm:1.8.0": version: 1.8.0 resolution: "web3-eth@npm:1.8.0" @@ -19562,28 +15126,6 @@ __metadata: languageName: node linkType: hard -"web3-net@npm:1.2.11": - version: 1.2.11 - resolution: "web3-net@npm:1.2.11" - dependencies: - web3-core: 1.2.11 - web3-core-method: 1.2.11 - web3-utils: 1.2.11 - checksum: 76a99815699674709b869b60bf950d20167b999fe93f7d091b01ce3fd0e3dd9c30ef3519156c04eb01703791c049b19b295e6901dd41d208ea600149961f7ee6 - languageName: node - linkType: hard - -"web3-net@npm:1.7.4": - version: 1.7.4 - resolution: "web3-net@npm:1.7.4" - dependencies: - web3-core: 1.7.4 - web3-core-method: 1.7.4 - web3-utils: 1.7.4 - checksum: 284af4860ad533bf791768ca273b5ab4dd1003d5808e4ead3c5b8e98f1ea7018ee2256032fd16ac2a5b3cabd64a6b361c6a6824949aafdb4ed25571fc7a48327 - languageName: node - linkType: hard - "web3-net@npm:1.8.0": version: 1.8.0 resolution: "web3-net@npm:1.8.0" @@ -19595,54 +15137,6 @@ __metadata: languageName: node linkType: hard -"web3-provider-engine@npm:14.2.1": - version: 14.2.1 - resolution: "web3-provider-engine@npm:14.2.1" - dependencies: - async: ^2.5.0 - backoff: ^2.5.0 - clone: ^2.0.0 - cross-fetch: ^2.1.0 - eth-block-tracker: ^3.0.0 - eth-json-rpc-infura: ^3.1.0 - eth-sig-util: ^1.4.2 - ethereumjs-block: ^1.2.2 - ethereumjs-tx: ^1.2.0 - ethereumjs-util: ^5.1.5 - ethereumjs-vm: ^2.3.4 - json-rpc-error: ^2.0.0 - json-stable-stringify: ^1.0.1 - promise-to-callback: ^1.0.0 - readable-stream: ^2.2.9 - request: ^2.85.0 - semaphore: ^1.0.3 - ws: ^5.1.1 - xhr: ^2.2.0 - xtend: ^4.0.1 - checksum: 45441e22633184bd5f6ea645e20f99c8002b3b64d3e564cd9d0f65bad7f0755ad2cdf9a88fcac9585e908aacea28cc6e80c0939498ee4f4c6c49107d16e011bf - languageName: node - linkType: hard - -"web3-providers-http@npm:1.2.11": - version: 1.2.11 - resolution: "web3-providers-http@npm:1.2.11" - dependencies: - web3-core-helpers: 1.2.11 - xhr2-cookies: 1.1.0 - checksum: 64760032d68826865de084c31d81be70bebc54cd82138ef724da13b60f7b341d4c0c6716912616b928680756ea6f2cef42be7d16fa9dd143a09ac55701232193 - languageName: node - linkType: hard - -"web3-providers-http@npm:1.7.4": - version: 1.7.4 - resolution: "web3-providers-http@npm:1.7.4" - dependencies: - web3-core-helpers: 1.7.4 - xhr2-cookies: 1.1.0 - checksum: 1235247870e0ad3326ac03cbb8b05730fa864e8aae74b37d9ed96dbfc4b328db57144bc697b33f5551ef8e42a37828f7b61680a863316bcaed09b677afab6b05 - languageName: node - linkType: hard - "web3-providers-http@npm:1.8.0": version: 1.8.0 resolution: "web3-providers-http@npm:1.8.0" @@ -19655,27 +15149,6 @@ __metadata: languageName: node linkType: hard -"web3-providers-ipc@npm:1.2.11": - version: 1.2.11 - resolution: "web3-providers-ipc@npm:1.2.11" - dependencies: - oboe: 2.1.4 - underscore: 1.9.1 - web3-core-helpers: 1.2.11 - checksum: 0fab2f824e4c7f080fee26b76c9c8448eb51abfd285a04f3c9efe92c3b9a8742096804ec02f56bc8297e375ea12f0f2205bb6c0ae376c44c005cdfeec65d0b7e - languageName: node - linkType: hard - -"web3-providers-ipc@npm:1.7.4": - version: 1.7.4 - resolution: "web3-providers-ipc@npm:1.7.4" - dependencies: - oboe: 2.1.5 - web3-core-helpers: 1.7.4 - checksum: e421d788e942cd834e56ecd1face56b987a5d0454602ed78fd94fdb618608d0338f17b23b908d6f4aa3c03032d7807180fd99a07cbf081a5498f7363f95f843f - languageName: node - linkType: hard - "web3-providers-ipc@npm:1.8.0": version: 1.8.0 resolution: "web3-providers-ipc@npm:1.8.0" @@ -19686,29 +15159,6 @@ __metadata: languageName: node linkType: hard -"web3-providers-ws@npm:1.2.11": - version: 1.2.11 - resolution: "web3-providers-ws@npm:1.2.11" - dependencies: - eventemitter3: 4.0.4 - underscore: 1.9.1 - web3-core-helpers: 1.2.11 - websocket: ^1.0.31 - checksum: 4a4c591c2bd9724748e9dba124e59048b91239aa7cd435394f2a1d8e7914132920a17e56bc646f46912844fcfbbc38333b7023ebec298af36106ec4814d2ff5c - languageName: node - linkType: hard - -"web3-providers-ws@npm:1.7.4": - version: 1.7.4 - resolution: "web3-providers-ws@npm:1.7.4" - dependencies: - eventemitter3: 4.0.4 - web3-core-helpers: 1.7.4 - websocket: ^1.0.32 - checksum: 3be6fe08853d1370644bae18a55fec702ef4d66089f09ea59206ed923599e365ccbff58d8e1e04743f623c49e259fe45d2862064166b2bcd6ca2943686a90010 - languageName: node - linkType: hard - "web3-providers-ws@npm:1.8.0": version: 1.8.0 resolution: "web3-providers-ws@npm:1.8.0" @@ -19720,30 +15170,6 @@ __metadata: languageName: node linkType: hard -"web3-shh@npm:1.2.11": - version: 1.2.11 - resolution: "web3-shh@npm:1.2.11" - dependencies: - web3-core: 1.2.11 - web3-core-method: 1.2.11 - web3-core-subscriptions: 1.2.11 - web3-net: 1.2.11 - checksum: 64c4a1f03bc3975a2baff9fa6d89a0050a06f179f1ec4d6e28f480b761d0efe56a9a79a5a320821e1dd503e82d44e73dd69b883b9e69d96cced3f979e0a3f4ff - languageName: node - linkType: hard - -"web3-shh@npm:1.7.4": - version: 1.7.4 - resolution: "web3-shh@npm:1.7.4" - dependencies: - web3-core: 1.7.4 - web3-core-method: 1.7.4 - web3-core-subscriptions: 1.7.4 - web3-net: 1.7.4 - checksum: debdd0f8fae5ca82c14ed9cc59872a2fa63a800804ac4b355f4f9b1a030e0b1cc298b6fc6367e7d6312f5702bc1b42f419e541beed4289d4d0ff411bde6154cb - languageName: node - linkType: hard - "web3-shh@npm:1.8.0": version: 1.8.0 resolution: "web3-shh@npm:1.8.0" @@ -19756,22 +15182,6 @@ __metadata: languageName: node linkType: hard -"web3-utils@npm:1.2.11": - version: 1.2.11 - resolution: "web3-utils@npm:1.2.11" - dependencies: - bn.js: ^4.11.9 - eth-lib: 0.2.8 - ethereum-bloom-filters: ^1.0.6 - ethjs-unit: 0.1.6 - number-to-bn: 1.7.0 - randombytes: ^2.1.0 - underscore: 1.9.1 - utf8: 3.0.0 - checksum: 1e43235963d5176e447b20b201a66fabccbe7bd4ef8bbb2edfa5ea80a41e8202a8e8f3db128b2a1662855a627a52d100e3207b81a739b937b5b3b4f9114c008f - languageName: node - linkType: hard - "web3-utils@npm:1.7.0": version: 1.7.0 resolution: "web3-utils@npm:1.7.0" @@ -19787,9 +15197,9 @@ __metadata: languageName: node linkType: hard -"web3-utils@npm:1.7.4": - version: 1.7.4 - resolution: "web3-utils@npm:1.7.4" +"web3-utils@npm:1.8.0": + version: 1.8.0 + resolution: "web3-utils@npm:1.8.0" dependencies: bn.js: ^5.2.1 ethereum-bloom-filters: ^1.0.6 @@ -19798,52 +15208,23 @@ __metadata: number-to-bn: 1.7.0 randombytes: ^2.1.0 utf8: 3.0.0 - checksum: 5d9256366904e5c24c7198a8791aa76217100aa068650ccc18264ff670d1e8d42d40fcc5ddc66e3c05fac3b480753ccf7e519709e60aefd73d71dd4c4d2adcbb + checksum: 9ac6b8be14fd1feb8f6744d97f94a043716f360035f07de5a6ab414b25838922ac06e09141af39f66fbf3e76de5f1c3e07807929adf754a28ac2159e32dacedf languageName: node linkType: hard -"web3-utils@npm:1.8.0, web3-utils@npm:^1.0.0-beta.31, web3-utils@npm:^1.3.0": - version: 1.8.0 - resolution: "web3-utils@npm:1.8.0" +"web3-utils@npm:^1.3.6": + version: 1.10.4 + resolution: "web3-utils@npm:1.10.4" dependencies: + "@ethereumjs/util": ^8.1.0 bn.js: ^5.2.1 ethereum-bloom-filters: ^1.0.6 - ethereumjs-util: ^7.1.0 + ethereum-cryptography: ^2.1.2 ethjs-unit: 0.1.6 number-to-bn: 1.7.0 randombytes: ^2.1.0 utf8: 3.0.0 - checksum: 9ac6b8be14fd1feb8f6744d97f94a043716f360035f07de5a6ab414b25838922ac06e09141af39f66fbf3e76de5f1c3e07807929adf754a28ac2159e32dacedf - languageName: node - linkType: hard - -"web3@npm:1.2.11": - version: 1.2.11 - resolution: "web3@npm:1.2.11" - dependencies: - web3-bzz: 1.2.11 - web3-core: 1.2.11 - web3-eth: 1.2.11 - web3-eth-personal: 1.2.11 - web3-net: 1.2.11 - web3-shh: 1.2.11 - web3-utils: 1.2.11 - checksum: c4fa6ddaddc2de31c561590eb3703e9446c0a9bd87155f536fd72c3c22337056bbd045baf36fec6152e58ae67e552fffad29e794030cd87634becb99a079e91f - languageName: node - linkType: hard - -"web3@npm:1.7.4": - version: 1.7.4 - resolution: "web3@npm:1.7.4" - dependencies: - web3-bzz: 1.7.4 - web3-core: 1.7.4 - web3-eth: 1.7.4 - web3-eth-personal: 1.7.4 - web3-net: 1.7.4 - web3-shh: 1.7.4 - web3-utils: 1.7.4 - checksum: 1597b099e1694a96cc7683e954800049fa109499eae45bd6f44f48dd868dcc92213d1fd6f651c6af13331b77e00f2a8d21ff6a113b703728c45eb42b99541d7c + checksum: a1535817a4653f1b5cc868aa19305158122379078a41e13642e1ba64803f6f8e5dd2fb8c45c033612b8f52dde42d8008afce85296c0608276fe1513dece66a49 languageName: node linkType: hard @@ -19882,21 +15263,7 @@ __metadata: languageName: node linkType: hard -"websocket@npm:1.0.32": - version: 1.0.32 - resolution: "websocket@npm:1.0.32" - dependencies: - bufferutil: ^4.0.1 - debug: ^2.2.0 - es5-ext: ^0.10.50 - typedarray-to-buffer: ^3.1.5 - utf-8-validate: ^5.0.2 - yaeti: ^0.0.6 - checksum: a29777a1942bf802f955782c7cf948797d19731a911b81adb957873e74b1d5356c621f217a972b075ecf04417a76897ea98dbfc19394007c4cf5e97cd4d494ac - languageName: node - linkType: hard - -"websocket@npm:^1.0.31, websocket@npm:^1.0.32": +"websocket@npm:^1.0.32": version: 1.0.34 resolution: "websocket@npm:1.0.34" dependencies: @@ -19910,13 +15277,6 @@ __metadata: languageName: node linkType: hard -"whatwg-fetch@npm:^2.0.4": - version: 2.0.4 - resolution: "whatwg-fetch@npm:2.0.4" - checksum: de7c65a68d7d62e2f144a6b30293370b3ad82b65ebcd68f2ac8e8bbe7ede90febd98ba9486b78c1cbc950e0e8838fa5c2727f939899ab3fc7b71a04be52d33a5 - languageName: node - linkType: hard - "whatwg-url@npm:^5.0.0": version: 5.0.0 resolution: "whatwg-url@npm:5.0.0" @@ -19940,13 +15300,6 @@ __metadata: languageName: node linkType: hard -"which-module@npm:^1.0.0": - version: 1.0.0 - resolution: "which-module@npm:1.0.0" - checksum: 98434f7deb36350cb543c1f15612188541737e1f12d39b23b1c371dff5cf4aa4746210f2bdec202d5fe9da8682adaf8e3f7c44c520687d30948cfc59d5534edb - languageName: node - linkType: hard - "which-module@npm:^2.0.0": version: 2.0.0 resolution: "which-module@npm:2.0.0" @@ -20030,16 +15383,14 @@ __metadata: languageName: node linkType: hard -"window-size@npm:^0.2.0": - version: 0.2.0 - resolution: "window-size@npm:0.2.0" - bin: - window-size: cli.js - checksum: a85e2acf156cfa194301294809867bdadd8a48ee5d972d9fa8e3e1b3420a1d0201b13ac8eb0348a0d14bbf2c3316565b6a749749c2384c5d286caf8a064c4f90 +"word-wrap@npm:^1.2.5": + version: 1.2.5 + resolution: "word-wrap@npm:1.2.5" + checksum: f93ba3586fc181f94afdaff3a6fef27920b4b6d9eaefed0f428f8e07adea2a7f54a5f2830ce59406c8416f033f86902b91eb824072354645eea687dff3691ccb languageName: node linkType: hard -"word-wrap@npm:^1.2.3, word-wrap@npm:~1.2.3": +"word-wrap@npm:~1.2.3": version: 1.2.3 resolution: "word-wrap@npm:1.2.3" checksum: 30b48f91fcf12106ed3186ae4fa86a6a1842416df425be7b60485de14bec665a54a68e4b5156647dec3a70f25e84d270ca8bc8cd23182ed095f5c7206a938c1f @@ -20077,6 +15428,13 @@ __metadata: languageName: node linkType: hard +"workerpool@npm:^6.5.1": + version: 6.5.1 + resolution: "workerpool@npm:6.5.1" + checksum: f86d13f9139c3a57c5a5867e81905cd84134b499849405dec2ffe5b1acd30dabaa1809f6f6ee603a7c65e1e4325f21509db6b8398eaf202c8b8f5809e26a2e16 + languageName: node + linkType: hard + "wrap-ansi@npm:^2.0.0": version: 2.1.0 resolution: "wrap-ansi@npm:2.1.0" @@ -20181,15 +15539,6 @@ __metadata: languageName: node linkType: hard -"ws@npm:^5.1.1": - version: 5.2.3 - resolution: "ws@npm:5.2.3" - dependencies: - async-limiter: ~1.0.0 - checksum: bdb2223a40c2c68cf91b25a6c9b8c67d5275378ec6187f343314d3df7530e55b77cb9fe79fb1c6a9758389ac5aefc569d24236924b5c65c5dbbaff409ef739fc - languageName: node - linkType: hard - "ws@npm:^7.4.5, ws@npm:^7.4.6": version: 7.5.9 resolution: "ws@npm:7.5.9" @@ -20244,16 +15593,7 @@ __metadata: languageName: node linkType: hard -"xhr2-cookies@npm:1.1.0": - version: 1.1.0 - resolution: "xhr2-cookies@npm:1.1.0" - dependencies: - cookiejar: ^2.1.1 - checksum: 6a9fc45f3490cc53e6a308bd7164dab07ecb94f6345e78951ed4a1e8f8c4c7707a1b039a6b4ef7c9d611d9465d6f94d7d4260c43bc34eed8d6f9210a775eb719 - languageName: node - linkType: hard - -"xhr@npm:^2.0.4, xhr@npm:^2.2.0, xhr@npm:^2.3.3": +"xhr@npm:^2.0.4, xhr@npm:^2.3.3": version: 2.6.0 resolution: "xhr@npm:2.6.0" dependencies: @@ -20272,29 +15612,13 @@ __metadata: languageName: node linkType: hard -"xtend@npm:^4.0.0, xtend@npm:^4.0.1, xtend@npm:^4.0.2, xtend@npm:~4.0.0, xtend@npm:~4.0.1": +"xtend@npm:^4.0.0": version: 4.0.2 resolution: "xtend@npm:4.0.2" checksum: ac5dfa738b21f6e7f0dd6e65e1b3155036d68104e67e5d5d1bde74892e327d7e5636a076f625599dc394330a731861e87343ff184b0047fef1360a7ec0a5a36a languageName: node linkType: hard -"xtend@npm:~2.1.1": - version: 2.1.2 - resolution: "xtend@npm:2.1.2" - dependencies: - object-keys: ~0.4.0 - checksum: a8b79f31502c163205984eaa2b196051cd2fab0882b49758e30f2f9018255bc6c462e32a090bf3385d1bda04755ad8cc0052a09e049b0038f49eb9b950d9c447 - languageName: node - linkType: hard - -"y18n@npm:^3.2.1": - version: 3.2.2 - resolution: "y18n@npm:3.2.2" - checksum: 6154fd7544f8bbf5b18cdf77692ed88d389be49c87238ecb4e0d6a5276446cd2a5c29cc4bdbdddfc7e4e498b08df9d7e38df4a1453cf75eecfead392246ea74a - languageName: node - linkType: hard - "y18n@npm:^4.0.0": version: 4.0.3 resolution: "y18n@npm:4.0.3" @@ -20316,7 +15640,7 @@ __metadata: languageName: node linkType: hard -"yallist@npm:^3.0.0, yallist@npm:^3.0.2, yallist@npm:^3.1.1": +"yallist@npm:^3.0.0, yallist@npm:^3.1.1": version: 3.1.1 resolution: "yallist@npm:3.1.1" checksum: 48f7bb00dc19fc635a13a39fe547f527b10c9290e7b3e836b9a8f1ca04d4d342e85714416b3c2ab74949c9c66f9cebb0473e6bc353b79035356103b47641285d @@ -20337,7 +15661,7 @@ __metadata: languageName: node linkType: hard -"yargs-parser@npm:13.1.2, yargs-parser@npm:^13.1.0, yargs-parser@npm:^13.1.2": +"yargs-parser@npm:13.1.2, yargs-parser@npm:^13.1.2": version: 13.1.2 resolution: "yargs-parser@npm:13.1.2" dependencies: @@ -20354,17 +15678,7 @@ __metadata: languageName: node linkType: hard -"yargs-parser@npm:^2.4.1": - version: 2.4.1 - resolution: "yargs-parser@npm:2.4.1" - dependencies: - camelcase: ^3.0.0 - lodash.assign: ^4.0.6 - checksum: f57946a93a9e0986fccbc7999a3fc8179d4693e4551ef0ace3d599c38ec004a3783efb9eed9fa5d738b30db1cfa1d3a07f4dd6ae060cfce6fe61c3ae7b7a347b - languageName: node - linkType: hard - -"yargs-parser@npm:^20.2.2": +"yargs-parser@npm:^20.2.2, yargs-parser@npm:^20.2.9": version: 20.2.9 resolution: "yargs-parser@npm:20.2.9" checksum: 8bb69015f2b0ff9e17b2c8e6bfe224ab463dd00ca211eece72a4cd8a906224d2703fb8a326d36fdd0e68701e201b2a60ed7cf81ce0fd9b3799f9fe7745977ae3 @@ -20389,7 +15703,7 @@ __metadata: languageName: node linkType: hard -"yargs-unparser@npm:2.0.0": +"yargs-unparser@npm:2.0.0, yargs-unparser@npm:^2.0.0": version: 2.0.0 resolution: "yargs-unparser@npm:2.0.0" dependencies: @@ -20401,25 +15715,6 @@ __metadata: languageName: node linkType: hard -"yargs@npm:13.2.4": - version: 13.2.4 - resolution: "yargs@npm:13.2.4" - dependencies: - cliui: ^5.0.0 - find-up: ^3.0.0 - get-caller-file: ^2.0.1 - os-locale: ^3.1.0 - require-directory: ^2.1.1 - require-main-filename: ^2.0.0 - set-blocking: ^2.0.0 - string-width: ^3.0.0 - which-module: ^2.0.0 - y18n: ^4.0.0 - yargs-parser: ^13.1.0 - checksum: c056449e069e0ba5dc1720a82134e9b0c8c5d8720f84d3b7be98c0fef747b8d15812de5c7fc7a2ee3be68fec69751cdf30389bd31e35f37cf4e1b912fbad8996 - languageName: node - linkType: hard - "yargs@npm:13.3.2, yargs@npm:^13.3.0": version: 13.3.2 resolution: "yargs@npm:13.3.2" @@ -20438,7 +15733,7 @@ __metadata: languageName: node linkType: hard -"yargs@npm:16.2.0": +"yargs@npm:16.2.0, yargs@npm:^16.2.0": version: 16.2.0 resolution: "yargs@npm:16.2.0" dependencies: @@ -20453,28 +15748,6 @@ __metadata: languageName: node linkType: hard -"yargs@npm:^4.7.1": - version: 4.8.1 - resolution: "yargs@npm:4.8.1" - dependencies: - cliui: ^3.2.0 - decamelize: ^1.1.1 - get-caller-file: ^1.0.1 - lodash.assign: ^4.0.3 - os-locale: ^1.4.0 - read-pkg-up: ^1.0.1 - require-directory: ^2.1.1 - require-main-filename: ^1.0.1 - set-blocking: ^2.0.0 - string-width: ^1.0.1 - which-module: ^1.0.0 - window-size: ^0.2.0 - y18n: ^3.2.1 - yargs-parser: ^2.4.1 - checksum: 5d0a45dceaf8cff1c6a7164b2c944755a09cced3cb1d585bbc79ffed758ef9f9b54ead0879e3dacfc696ccd15fec9e6e29183c24517d7f578b47cd0614a3851d - languageName: node - linkType: hard - "yn@npm:3.1.1": version: 3.1.1 resolution: "yn@npm:3.1.1" From 6f9af8f1553d24e1efcdbd5e308b2269026bcb9d Mon Sep 17 00:00:00 2001 From: Ethereumdegen Date: Mon, 2 Mar 2026 13:43:10 -0500 Subject: [PATCH 45/46] adding pools v3 subgraph --- package.json | 3 +- packages/subgraph-pool-v2/README.md | 2 +- packages/subgraph-pool-v2/config/bnb.json | 26 + packages/subgraph-pool-v2/subgraph.yaml | 14 +- .../abis/CollateralManager.json | 772 ++++ packages/subgraph-pool-v3/abis/Factory.json | 201 + packages/subgraph-pool-v3/abis/PoolV3.json | 1929 ++++++++++ .../subgraph-pool-v3/config/apechain.json | 1 + packages/subgraph-pool-v3/config/base.json | 1 + .../CollateralManager/CollateralManager.ts | 1428 +++++++ .../generated/Factory/Factory.ts | 383 ++ packages/subgraph-pool-v3/generated/schema.ts | 3334 +++++++++++++++++ .../subgraph-pool-v3/generated/templates.ts | 17 + .../generated/templates/Pool/Factory.ts | 383 ++ .../generated/templates/Pool/Pool.ts | 3031 +++++++++++++++ packages/subgraph-pool-v3/package.json | 57 + .../scripts/generate-subgraph.js | 41 + .../subgraph-pool-v3/src/graphql.config.yml | 18 + .../src/mappings/collateralManager.ts | 50 + .../subgraph-pool-v3/src/mappings/core.ts | 463 +++ .../subgraph-pool-v3/src/mappings/factory.ts | 55 + packages/subgraph-pool-v3/src/schema.graphql | 324 ++ .../subgraph-pool-v3/subgraph.template.yaml | 81 + packages/subgraph-pool-v3/subgraph.yaml | 81 + packages/subgraph-pool-v3/tsconfig.json | 15 + yarn.lock | 41 + 26 files changed, 12742 insertions(+), 9 deletions(-) create mode 100644 packages/subgraph-pool-v2/config/bnb.json create mode 100644 packages/subgraph-pool-v3/abis/CollateralManager.json create mode 100644 packages/subgraph-pool-v3/abis/Factory.json create mode 100644 packages/subgraph-pool-v3/abis/PoolV3.json create mode 100644 packages/subgraph-pool-v3/config/apechain.json create mode 100644 packages/subgraph-pool-v3/config/base.json create mode 100644 packages/subgraph-pool-v3/generated/CollateralManager/CollateralManager.ts create mode 100644 packages/subgraph-pool-v3/generated/Factory/Factory.ts create mode 100644 packages/subgraph-pool-v3/generated/schema.ts create mode 100644 packages/subgraph-pool-v3/generated/templates.ts create mode 100644 packages/subgraph-pool-v3/generated/templates/Pool/Factory.ts create mode 100644 packages/subgraph-pool-v3/generated/templates/Pool/Pool.ts create mode 100644 packages/subgraph-pool-v3/package.json create mode 100644 packages/subgraph-pool-v3/scripts/generate-subgraph.js create mode 100644 packages/subgraph-pool-v3/src/graphql.config.yml create mode 100644 packages/subgraph-pool-v3/src/mappings/collateralManager.ts create mode 100644 packages/subgraph-pool-v3/src/mappings/core.ts create mode 100644 packages/subgraph-pool-v3/src/mappings/factory.ts create mode 100644 packages/subgraph-pool-v3/src/schema.graphql create mode 100644 packages/subgraph-pool-v3/subgraph.template.yaml create mode 100644 packages/subgraph-pool-v3/subgraph.yaml create mode 100644 packages/subgraph-pool-v3/tsconfig.json diff --git a/package.json b/package.json index e6388a5a0..89041373a 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,8 @@ "packages/services", "packages/subgraph", "packages/subgraph-pool", - "packages/subgraph-pool-v2" + "packages/subgraph-pool-v2", + "packages/subgraph-pool-v3" ] }, "packageManager": "yarn@3.6.1", diff --git a/packages/subgraph-pool-v2/README.md b/packages/subgraph-pool-v2/README.md index b616b6e13..3d334d06c 100644 --- a/packages/subgraph-pool-v2/README.md +++ b/packages/subgraph-pool-v2/README.md @@ -80,7 +80,7 @@ npm run codegen && npm run build yarn deploy_ormi teller-pools-v2-mainnet yarn deploy_ormi teller-pools-v2-base - + yarn deploy_ormi teller-pools-v2-apechain ``` diff --git a/packages/subgraph-pool-v2/config/bnb.json b/packages/subgraph-pool-v2/config/bnb.json new file mode 100644 index 000000000..5076737ef --- /dev/null +++ b/packages/subgraph-pool-v2/config/bnb.json @@ -0,0 +1,26 @@ +{ + "enabled": true, + "name": "tellerv2-poolsv2-bnb", + "network": "bsc", + "export_network_name": "bnb", + "product": "studio", + "studio": { + "owner": "0x1a76339211668a6939e1d6D13AB902bBef5D9ebc", + "network": "arbitrum-one" + }, + "grafting": { + "enabled": false + }, + "contracts": { + "factory": { + "enabled": true, + "address": "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa", + "block": "81088797" + }, + "collateralManager": { + "enabled": true, + "address": "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295", + "block": "81088797" + } + } +} diff --git a/packages/subgraph-pool-v2/subgraph.yaml b/packages/subgraph-pool-v2/subgraph.yaml index fb07b9329..61026d4c1 100644 --- a/packages/subgraph-pool-v2/subgraph.yaml +++ b/packages/subgraph-pool-v2/subgraph.yaml @@ -9,11 +9,11 @@ features: dataSources: - kind: ethereum/contract name: Factory - network: katana + network: bsc source: abi: Factory - address: "0x3D495036Dfeb1bBfCCabAC74e90e01cDD5C8E578" - startBlock: 6541463 + address: "0x0EfD3E33Ba2EdE028e50a3E7f81E084996d161aa" + startBlock: 81088797 mapping: kind: ethereum/events apiVersion: 0.0.7 @@ -29,11 +29,11 @@ dataSources: handler: handleLenderGroupDeployed - kind: ethereum/contract name: CollateralManager - network: katana + network: bsc source: abi: CollateralManager - address: "0x6455F2E1CCb14bd0b675A309276FB5333Dec524f" - startBlock: 6541463 + address: "0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295" + startBlock: 81088797 mapping: kind: ethereum/events apiVersion: 0.0.7 @@ -51,7 +51,7 @@ dataSources: templates: - kind: ethereum/contract name: Pool - network: katana + network: bsc source: abi: Pool mapping: diff --git a/packages/subgraph-pool-v3/abis/CollateralManager.json b/packages/subgraph-pool-v3/abis/CollateralManager.json new file mode 100644 index 000000000..b2bb38c1e --- /dev/null +++ b/packages/subgraph-pool-v3/abis/CollateralManager.json @@ -0,0 +1,772 @@ +[ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "CollateralClaimed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "enum CollateralType", + "name": "_type", + "type": "uint8" + }, + { + "indexed": false, + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + } + ], + "name": "CollateralCommitted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "enum CollateralType", + "name": "_type", + "type": "uint8" + }, + { + "indexed": false, + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + } + ], + "name": "CollateralDeposited", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "_collateralEscrow", + "type": "address" + } + ], + "name": "CollateralEscrowDeployed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "enum CollateralType", + "name": "_type", + "type": "uint8" + }, + { + "indexed": false, + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "_recipient", + "type": "address" + } + ], + "name": "CollateralWithdrawn", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "_escrows", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_borrowerAddress", + "type": "address" + }, + { + "components": [ + { + "internalType": "enum CollateralType", + "name": "_collateralType", + "type": "uint8" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + } + ], + "internalType": "struct Collateral[]", + "name": "_collateralInfo", + "type": "tuple[]" + } + ], + "name": "checkBalances", + "outputs": [ + { + "internalType": "bool", + "name": "validated_", + "type": "bool" + }, + { + "internalType": "bool[]", + "name": "checks_", + "type": "bool[]" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "components": [ + { + "internalType": "enum CollateralType", + "name": "_collateralType", + "type": "uint8" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + } + ], + "internalType": "struct Collateral[]", + "name": "_collateralInfo", + "type": "tuple[]" + } + ], + "name": "commitCollateral", + "outputs": [ + { + "internalType": "bool", + "name": "validation_", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "components": [ + { + "internalType": "enum CollateralType", + "name": "_collateralType", + "type": "uint8" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + } + ], + "internalType": "struct Collateral", + "name": "_collateralInfo", + "type": "tuple" + } + ], + "name": "commitCollateral", + "outputs": [ + { + "internalType": "bool", + "name": "validation_", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "deployAndDeposit", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + } + ], + "name": "getCollateralAmount", + "outputs": [ + { + "internalType": "uint256", + "name": "amount_", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getCollateralEscrowBeacon", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "getCollateralInfo", + "outputs": [ + { + "components": [ + { + "internalType": "enum CollateralType", + "name": "_collateralType", + "type": "uint8" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_tokenId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralAddress", + "type": "address" + } + ], + "internalType": "struct Collateral[]", + "name": "infos_", + "type": "tuple[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "getEscrow", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_collateralEscrowBeacon", + "type": "address" + }, + { + "internalType": "address", + "name": "_tellerV2", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "isBidCollateralBacked", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "lenderClaimCollateral", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralRecipient", + "type": "address" + } + ], + "name": "lenderClaimCollateralWithRecipient", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_liquidatorAddress", + "type": "address" + } + ], + "name": "liquidateCollateral", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256[]", + "name": "_ids", + "type": "uint256[]" + }, + { + "internalType": "uint256[]", + "name": "_values", + "type": "uint256[]" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155BatchReceived", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "id", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC1155Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "address", + "name": "", + "type": "address" + }, + { + "internalType": "uint256", + "name": "", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "", + "type": "bytes" + } + ], + "name": "onERC721Received", + "outputs": [ + { + "internalType": "bytes4", + "name": "", + "type": "bytes4" + } + ], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "revalidateCollateral", + "outputs": [ + { + "internalType": "bool", + "name": "validation_", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_collateralEscrowBeacon", + "type": "address" + } + ], + "name": "setCollateralEscrowBeacon", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "tellerV2", + "outputs": [ + { + "internalType": "contract ITellerV2", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + } + ], + "name": "withdraw", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_tokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_recipientAddress", + "type": "address" + } + ], + "name": "withdrawDustTokens", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ] \ No newline at end of file diff --git a/packages/subgraph-pool-v3/abis/Factory.json b/packages/subgraph-pool-v3/abis/Factory.json new file mode 100644 index 000000000..938f0c422 --- /dev/null +++ b/packages/subgraph-pool-v3/abis/Factory.json @@ -0,0 +1,201 @@ +[ + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "groupContract", + "type": "address" + } + ], + "name": "DeployedLenderGroupContract", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_initialPrincipalAmount", + "type": "uint256" + }, + { + "components": [ + { + "internalType": "address", + "name": "principalTokenAddress", + "type": "address" + }, + { + "internalType": "address", + "name": "collateralTokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "marketId", + "type": "uint256" + }, + { + "internalType": "uint32", + "name": "maxLoanDuration", + "type": "uint32" + }, + { + "internalType": "uint16", + "name": "interestRateLowerBound", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "interestRateUpperBound", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "liquidityThresholdPercent", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "collateralRatio", + "type": "uint16" + } + ], + "internalType": "struct ILenderCommitmentGroup_V3.CommitmentGroupConfig", + "name": "_commitmentGroupConfig", + "type": "tuple" + }, + { + "internalType": "address", + "name": "_priceAdapterAddress", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_priceAdapterRoute", + "type": "bytes" + } + ], + "name": "deployLenderCommitmentGroupPool", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "deployedLenderGroupContracts", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_lenderGroupBeacon", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "lenderGroupBeacon", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +] \ No newline at end of file diff --git a/packages/subgraph-pool-v3/abis/PoolV3.json b/packages/subgraph-pool-v3/abis/PoolV3.json new file mode 100644 index 000000000..6c50e4468 --- /dev/null +++ b/packages/subgraph-pool-v3/abis/PoolV3.json @@ -0,0 +1,1929 @@ +[ + { + "inputs": [ + { + "internalType": "address", + "name": "_tellerV2", + "type": "address" + }, + { + "internalType": "address", + "name": "_smartCommitmentForwarder", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "borrower", + "type": "address" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "bidId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "principalAmount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "collateralAmount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint32", + "name": "loanDuration", + "type": "uint32" + }, + { + "indexed": false, + "internalType": "uint16", + "name": "interestRate", + "type": "uint16" + } + ], + "name": "BorrowerAcceptedFunds", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "bidId", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "liquidator", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amountDue", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "int256", + "name": "tokenAmountDifference", + "type": "int256" + } + ], + "name": "DefaultedLoanLiquidated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "caller", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Deposit", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "bidId", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "repayer", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "principalAmount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "interestAmount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "totalPrincipalRepaid", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "totalInterestCollected", + "type": "uint256" + } + ], + "name": "LoanRepaid", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "PausedBorrowing", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "PausedLiquidationAuction", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "principalTokenAddress", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "collateralTokenAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "marketId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint32", + "name": "maxLoanDuration", + "type": "uint32" + }, + { + "indexed": false, + "internalType": "uint16", + "name": "interestRateLowerBound", + "type": "uint16" + }, + { + "indexed": false, + "internalType": "uint16", + "name": "interestRateUpperBound", + "type": "uint16" + }, + { + "indexed": false, + "internalType": "uint16", + "name": "liquidityThresholdPercent", + "type": "uint16" + }, + { + "indexed": false, + "internalType": "uint16", + "name": "loanToValuePercent", + "type": "uint16" + } + ], + "name": "PoolInitialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "transferredAt", + "type": "uint256" + } + ], + "name": "SharesLastTransferredAt", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "UnpausedBorrowing", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "UnpausedLiquidationAuction", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "caller", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Withdraw", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "WithdrawFromEscrow", + "type": "event" + }, + { + "inputs": [], + "name": "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "EXCHANGE_RATE_EXPANSION_FACTOR", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "MAX_WITHDRAW_DELAY_TIME", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "MIN_TWAP_INTERVAL", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "ORACLE_MANAGER", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "SMART_COMMITMENT_FORWARDER", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "TELLER_V2", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "UNISWAP_EXPANSION_FACTOR", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_borrower", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_principalAmount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_collateralAmount", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_collateralTokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_collateralTokenId", + "type": "uint256" + }, + { + "internalType": "uint32", + "name": "_loanDuration", + "type": "uint32" + }, + { + "internalType": "uint16", + "name": "_interestRate", + "type": "uint16" + } + ], + "name": "acceptFundsForAcceptBid", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "activeBids", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "activeBidsAmountDueRemaining", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "asset", + "outputs": [ + { + "internalType": "address", + "name": "assetTokenAddress", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "borrowingPaused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_principalAmount", + "type": "uint256" + } + ], + "name": "calculateCollateralRequiredToBorrowPrincipal", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "principalAmount", + "type": "uint256" + } + ], + "name": "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "outputs": [ + { + "internalType": "uint256", + "name": "collateralTokensAmountToMatchValue", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "collateralRatio", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "collateralToken", + "outputs": [ + { + "internalType": "contract IERC20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "convertToAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "convertToShares", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "decimals", + "outputs": [ + { + "internalType": "uint8", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "subtractedValue", + "type": "uint256" + } + ], + "name": "decreaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "excessivePrincipalTokensRepaid", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "firstDepositMade", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getCollateralTokenAddress", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getCollateralTokenType", + "outputs": [ + { + "internalType": "enum CommitmentCollateralType", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getLastUnpausedAt", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getMarketId", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getMaxLoanDuration", + "outputs": [ + { + "internalType": "uint32", + "name": "", + "type": "uint32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "amountDelta", + "type": "uint256" + } + ], + "name": "getMinInterestRate", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_amountOwed", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_loanDefaultedTimestamp", + "type": "uint256" + } + ], + "name": "getMinimumAmountDifferenceToCloseDefaultedLoan", + "outputs": [ + { + "internalType": "int256", + "name": "amountDifference_", + "type": "int256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "activeLoansAmountDelta", + "type": "uint256" + } + ], + "name": "getPoolUtilizationRatio", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getPrincipalAmountAvailableToBorrow", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getPrincipalTokenAddress", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "getSharesLastTransferredAt", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getTokenDifferenceFromLiquidations", + "outputs": [ + { + "internalType": "int256", + "name": "", + "type": "int256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "addedValue", + "type": "uint256" + } + ], + "name": "increaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "components": [ + { + "internalType": "address", + "name": "principalTokenAddress", + "type": "address" + }, + { + "internalType": "address", + "name": "collateralTokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "marketId", + "type": "uint256" + }, + { + "internalType": "uint32", + "name": "maxLoanDuration", + "type": "uint32" + }, + { + "internalType": "uint16", + "name": "interestRateLowerBound", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "interestRateUpperBound", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "liquidityThresholdPercent", + "type": "uint16" + }, + { + "internalType": "uint16", + "name": "collateralRatio", + "type": "uint16" + } + ], + "internalType": "struct ILenderCommitmentGroup_V3.CommitmentGroupConfig", + "name": "_commitmentGroupConfig", + "type": "tuple" + }, + { + "internalType": "address", + "name": "_priceAdapter", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_priceAdapterRoute", + "type": "bytes" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "interestRateLowerBound", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "interestRateUpperBound", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "lastUnpausedAt", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "int256", + "name": "_tokenAmountDifference", + "type": "int256" + } + ], + "name": "liquidateDefaultedLoanWithIncentive", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "liquidationAuctionPaused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "liquidityThresholdPercent", + "outputs": [ + { + "internalType": "uint16", + "name": "", + "type": "uint16" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "maxLoanDuration", + "outputs": [ + { + "internalType": "uint32", + "name": "", + "type": "uint32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "maxPrincipalPerCollateralAmount", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "mint", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "name", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pauseBorrowing", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "pauseLiquidationAuction", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "pausePool", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "priceAdapter", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "priceRouteHash", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "principalToken", + "outputs": [ + { + "internalType": "contract IERC20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "redeem", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_bidId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "repayer", + "type": "address" + }, + { + "internalType": "uint256", + "name": "principalAmount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "interestAmount", + "type": "uint256" + } + ], + "name": "repayLoanCallback", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_seconds", + "type": "uint256" + } + ], + "name": "setWithdrawDelayTime", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "sharesExchangeRate", + "outputs": [ + { + "internalType": "uint256", + "name": "rate_", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "sharesExchangeRateInverse", + "outputs": [ + { + "internalType": "uint256", + "name": "rate_", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "symbol", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalInterestCollected", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalPrincipalTokensCommitted", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalPrincipalTokensLended", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalPrincipalTokensRepaid", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalPrincipalTokensWithdrawn", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpauseBorrowing", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpauseLiquidationAuction", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpausePool", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "withdrawDelayTimeSeconds", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + } + ], + "name": "withdrawFromEscrowVault", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +] \ No newline at end of file diff --git a/packages/subgraph-pool-v3/config/apechain.json b/packages/subgraph-pool-v3/config/apechain.json new file mode 100644 index 000000000..ee73289b2 --- /dev/null +++ b/packages/subgraph-pool-v3/config/apechain.json @@ -0,0 +1 @@ +{"enabled":true,"name":"tellerv2-poolsv3-apechain","network":"apechain","export_network_name":"apechain","product":"studio","studio":{"owner":"0x1a76339211668a6939e1d6D13AB902bBef5D9ebc","network":"arbitrum-one"},"grafting":{"enabled":false},"contracts":{"factory":{"enabled":true,"address":"0x26E2BD4F67136a7929DFE82BD6392633eb5610C2","block":"34211523"}, "collateralManager":{"enabled":true,"address":"0x90D08f8Df66dFdE93801783FF7A36876453DAE75","block":"34211523"} } } diff --git a/packages/subgraph-pool-v3/config/base.json b/packages/subgraph-pool-v3/config/base.json new file mode 100644 index 000000000..7ce981ee9 --- /dev/null +++ b/packages/subgraph-pool-v3/config/base.json @@ -0,0 +1 @@ +{"enabled":true,"name":"tellerv2-poolsv3-base","network":"base","export_network_name":"base","product":"studio","studio":{"owner":"0x1a76339211668a6939e1d6D13AB902bBef5D9ebc","network":"arbitrum-one"},"grafting":{"enabled":false},"contracts":{"factory":{"enabled":true,"address":"0xD8D67872904Ee0778dFf44f05e6F2A7a246db10b","block":"32042817"}, "collateralManager":{"enabled":true,"address":"0x71B04a8569914bCb99D5F95644CF6b089c826024","block":"32042817"} } } diff --git a/packages/subgraph-pool-v3/generated/CollateralManager/CollateralManager.ts b/packages/subgraph-pool-v3/generated/CollateralManager/CollateralManager.ts new file mode 100644 index 000000000..bed4c4ba6 --- /dev/null +++ b/packages/subgraph-pool-v3/generated/CollateralManager/CollateralManager.ts @@ -0,0 +1,1428 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + ethereum, + JSONValue, + TypedMap, + Entity, + Bytes, + Address, + BigInt +} from "@graphprotocol/graph-ts"; + +export class CollateralClaimed extends ethereum.Event { + get params(): CollateralClaimed__Params { + return new CollateralClaimed__Params(this); + } +} + +export class CollateralClaimed__Params { + _event: CollateralClaimed; + + constructor(event: CollateralClaimed) { + this._event = event; + } + + get _bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } +} + +export class CollateralCommitted extends ethereum.Event { + get params(): CollateralCommitted__Params { + return new CollateralCommitted__Params(this); + } +} + +export class CollateralCommitted__Params { + _event: CollateralCommitted; + + constructor(event: CollateralCommitted) { + this._event = event; + } + + get _bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get _type(): i32 { + return this._event.parameters[1].value.toI32(); + } + + get _collateralAddress(): Address { + return this._event.parameters[2].value.toAddress(); + } + + get _amount(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get _tokenId(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } +} + +export class CollateralDeposited extends ethereum.Event { + get params(): CollateralDeposited__Params { + return new CollateralDeposited__Params(this); + } +} + +export class CollateralDeposited__Params { + _event: CollateralDeposited; + + constructor(event: CollateralDeposited) { + this._event = event; + } + + get _bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get _type(): i32 { + return this._event.parameters[1].value.toI32(); + } + + get _collateralAddress(): Address { + return this._event.parameters[2].value.toAddress(); + } + + get _amount(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get _tokenId(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } +} + +export class CollateralEscrowDeployed extends ethereum.Event { + get params(): CollateralEscrowDeployed__Params { + return new CollateralEscrowDeployed__Params(this); + } +} + +export class CollateralEscrowDeployed__Params { + _event: CollateralEscrowDeployed; + + constructor(event: CollateralEscrowDeployed) { + this._event = event; + } + + get _bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get _collateralEscrow(): Address { + return this._event.parameters[1].value.toAddress(); + } +} + +export class CollateralWithdrawn extends ethereum.Event { + get params(): CollateralWithdrawn__Params { + return new CollateralWithdrawn__Params(this); + } +} + +export class CollateralWithdrawn__Params { + _event: CollateralWithdrawn; + + constructor(event: CollateralWithdrawn) { + this._event = event; + } + + get _bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get _type(): i32 { + return this._event.parameters[1].value.toI32(); + } + + get _collateralAddress(): Address { + return this._event.parameters[2].value.toAddress(); + } + + get _amount(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get _tokenId(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } + + get _recipient(): Address { + return this._event.parameters[5].value.toAddress(); + } +} + +export class Initialized extends ethereum.Event { + get params(): Initialized__Params { + return new Initialized__Params(this); + } +} + +export class Initialized__Params { + _event: Initialized; + + constructor(event: Initialized) { + this._event = event; + } + + get version(): i32 { + return this._event.parameters[0].value.toI32(); + } +} + +export class OwnershipTransferred extends ethereum.Event { + get params(): OwnershipTransferred__Params { + return new OwnershipTransferred__Params(this); + } +} + +export class OwnershipTransferred__Params { + _event: OwnershipTransferred; + + constructor(event: OwnershipTransferred) { + this._event = event; + } + + get previousOwner(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get newOwner(): Address { + return this._event.parameters[1].value.toAddress(); + } +} + +export class CollateralManager__checkBalancesResult { + value0: boolean; + value1: Array; + + constructor(value0: boolean, value1: Array) { + this.value0 = value0; + this.value1 = value1; + } + + toMap(): TypedMap { + let map = new TypedMap(); + map.set("value0", ethereum.Value.fromBoolean(this.value0)); + map.set("value1", ethereum.Value.fromBooleanArray(this.value1)); + return map; + } + + getValidated_(): boolean { + return this.value0; + } + + getChecks_(): Array { + return this.value1; + } +} + +export class CollateralManager__checkBalancesInput_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CollateralManager__commitCollateralInput_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CollateralManager__commitCollateral1Input_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CollateralManager__getCollateralInfoResultInfos_Struct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CollateralManager extends ethereum.SmartContract { + static bind(address: Address): CollateralManager { + return new CollateralManager("CollateralManager", address); + } + + _escrows(param0: BigInt): Address { + let result = super.call("_escrows", "_escrows(uint256):(address)", [ + ethereum.Value.fromUnsignedBigInt(param0) + ]); + + return result[0].toAddress(); + } + + try__escrows(param0: BigInt): ethereum.CallResult
{ + let result = super.tryCall("_escrows", "_escrows(uint256):(address)", [ + ethereum.Value.fromUnsignedBigInt(param0) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + checkBalances( + _borrowerAddress: Address, + _collateralInfo: Array< + CollateralManager__checkBalancesInput_collateralInfoStruct + > + ): CollateralManager__checkBalancesResult { + let result = super.call( + "checkBalances", + "checkBalances(address,(uint8,uint256,uint256,address)[]):(bool,bool[])", + [ + ethereum.Value.fromAddress(_borrowerAddress), + ethereum.Value.fromTupleArray(_collateralInfo) + ] + ); + + return new CollateralManager__checkBalancesResult( + result[0].toBoolean(), + result[1].toBooleanArray() + ); + } + + try_checkBalances( + _borrowerAddress: Address, + _collateralInfo: Array< + CollateralManager__checkBalancesInput_collateralInfoStruct + > + ): ethereum.CallResult { + let result = super.tryCall( + "checkBalances", + "checkBalances(address,(uint8,uint256,uint256,address)[]):(bool,bool[])", + [ + ethereum.Value.fromAddress(_borrowerAddress), + ethereum.Value.fromTupleArray(_collateralInfo) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue( + new CollateralManager__checkBalancesResult( + value[0].toBoolean(), + value[1].toBooleanArray() + ) + ); + } + + commitCollateral( + _bidId: BigInt, + _collateralInfo: Array< + CollateralManager__commitCollateralInput_collateralInfoStruct + > + ): boolean { + let result = super.call( + "commitCollateral", + "commitCollateral(uint256,(uint8,uint256,uint256,address)[]):(bool)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromTupleArray(_collateralInfo) + ] + ); + + return result[0].toBoolean(); + } + + try_commitCollateral( + _bidId: BigInt, + _collateralInfo: Array< + CollateralManager__commitCollateralInput_collateralInfoStruct + > + ): ethereum.CallResult { + let result = super.tryCall( + "commitCollateral", + "commitCollateral(uint256,(uint8,uint256,uint256,address)[]):(bool)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromTupleArray(_collateralInfo) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + commitCollateral1( + _bidId: BigInt, + _collateralInfo: CollateralManager__commitCollateral1Input_collateralInfoStruct + ): boolean { + let result = super.call( + "commitCollateral", + "commitCollateral(uint256,(uint8,uint256,uint256,address)):(bool)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromTuple(_collateralInfo) + ] + ); + + return result[0].toBoolean(); + } + + try_commitCollateral1( + _bidId: BigInt, + _collateralInfo: CollateralManager__commitCollateral1Input_collateralInfoStruct + ): ethereum.CallResult { + let result = super.tryCall( + "commitCollateral", + "commitCollateral(uint256,(uint8,uint256,uint256,address)):(bool)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromTuple(_collateralInfo) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + getCollateralAmount(_bidId: BigInt, _collateralAddress: Address): BigInt { + let result = super.call( + "getCollateralAmount", + "getCollateralAmount(uint256,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromAddress(_collateralAddress) + ] + ); + + return result[0].toBigInt(); + } + + try_getCollateralAmount( + _bidId: BigInt, + _collateralAddress: Address + ): ethereum.CallResult { + let result = super.tryCall( + "getCollateralAmount", + "getCollateralAmount(uint256,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(_bidId), + ethereum.Value.fromAddress(_collateralAddress) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getCollateralEscrowBeacon(): Address { + let result = super.call( + "getCollateralEscrowBeacon", + "getCollateralEscrowBeacon():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_getCollateralEscrowBeacon(): ethereum.CallResult
{ + let result = super.tryCall( + "getCollateralEscrowBeacon", + "getCollateralEscrowBeacon():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + getCollateralInfo( + _bidId: BigInt + ): Array { + let result = super.call( + "getCollateralInfo", + "getCollateralInfo(uint256):((uint8,uint256,uint256,address)[])", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + + return result[0].toTupleArray< + CollateralManager__getCollateralInfoResultInfos_Struct + >(); + } + + try_getCollateralInfo( + _bidId: BigInt + ): ethereum.CallResult< + Array + > { + let result = super.tryCall( + "getCollateralInfo", + "getCollateralInfo(uint256):((uint8,uint256,uint256,address)[])", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue( + value[0].toTupleArray< + CollateralManager__getCollateralInfoResultInfos_Struct + >() + ); + } + + getEscrow(_bidId: BigInt): Address { + let result = super.call("getEscrow", "getEscrow(uint256):(address)", [ + ethereum.Value.fromUnsignedBigInt(_bidId) + ]); + + return result[0].toAddress(); + } + + try_getEscrow(_bidId: BigInt): ethereum.CallResult
{ + let result = super.tryCall("getEscrow", "getEscrow(uint256):(address)", [ + ethereum.Value.fromUnsignedBigInt(_bidId) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + isBidCollateralBacked(_bidId: BigInt): boolean { + let result = super.call( + "isBidCollateralBacked", + "isBidCollateralBacked(uint256):(bool)", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + + return result[0].toBoolean(); + } + + try_isBidCollateralBacked(_bidId: BigInt): ethereum.CallResult { + let result = super.tryCall( + "isBidCollateralBacked", + "isBidCollateralBacked(uint256):(bool)", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + onERC1155BatchReceived( + param0: Address, + param1: Address, + _ids: Array, + _values: Array, + param4: Bytes + ): Bytes { + let result = super.call( + "onERC1155BatchReceived", + "onERC1155BatchReceived(address,address,uint256[],uint256[],bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigIntArray(_ids), + ethereum.Value.fromUnsignedBigIntArray(_values), + ethereum.Value.fromBytes(param4) + ] + ); + + return result[0].toBytes(); + } + + try_onERC1155BatchReceived( + param0: Address, + param1: Address, + _ids: Array, + _values: Array, + param4: Bytes + ): ethereum.CallResult { + let result = super.tryCall( + "onERC1155BatchReceived", + "onERC1155BatchReceived(address,address,uint256[],uint256[],bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigIntArray(_ids), + ethereum.Value.fromUnsignedBigIntArray(_values), + ethereum.Value.fromBytes(param4) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBytes()); + } + + onERC1155Received( + param0: Address, + param1: Address, + id: BigInt, + value: BigInt, + param4: Bytes + ): Bytes { + let result = super.call( + "onERC1155Received", + "onERC1155Received(address,address,uint256,uint256,bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigInt(id), + ethereum.Value.fromUnsignedBigInt(value), + ethereum.Value.fromBytes(param4) + ] + ); + + return result[0].toBytes(); + } + + try_onERC1155Received( + param0: Address, + param1: Address, + id: BigInt, + value: BigInt, + param4: Bytes + ): ethereum.CallResult { + let result = super.tryCall( + "onERC1155Received", + "onERC1155Received(address,address,uint256,uint256,bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigInt(id), + ethereum.Value.fromUnsignedBigInt(value), + ethereum.Value.fromBytes(param4) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBytes()); + } + + onERC721Received( + param0: Address, + param1: Address, + param2: BigInt, + param3: Bytes + ): Bytes { + let result = super.call( + "onERC721Received", + "onERC721Received(address,address,uint256,bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigInt(param2), + ethereum.Value.fromBytes(param3) + ] + ); + + return result[0].toBytes(); + } + + try_onERC721Received( + param0: Address, + param1: Address, + param2: BigInt, + param3: Bytes + ): ethereum.CallResult { + let result = super.tryCall( + "onERC721Received", + "onERC721Received(address,address,uint256,bytes):(bytes4)", + [ + ethereum.Value.fromAddress(param0), + ethereum.Value.fromAddress(param1), + ethereum.Value.fromUnsignedBigInt(param2), + ethereum.Value.fromBytes(param3) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBytes()); + } + + owner(): Address { + let result = super.call("owner", "owner():(address)", []); + + return result[0].toAddress(); + } + + try_owner(): ethereum.CallResult
{ + let result = super.tryCall("owner", "owner():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + revalidateCollateral(_bidId: BigInt): boolean { + let result = super.call( + "revalidateCollateral", + "revalidateCollateral(uint256):(bool)", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + + return result[0].toBoolean(); + } + + try_revalidateCollateral(_bidId: BigInt): ethereum.CallResult { + let result = super.tryCall( + "revalidateCollateral", + "revalidateCollateral(uint256):(bool)", + [ethereum.Value.fromUnsignedBigInt(_bidId)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + tellerV2(): Address { + let result = super.call("tellerV2", "tellerV2():(address)", []); + + return result[0].toAddress(); + } + + try_tellerV2(): ethereum.CallResult
{ + let result = super.tryCall("tellerV2", "tellerV2():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } +} + +export class CheckBalancesCall extends ethereum.Call { + get inputs(): CheckBalancesCall__Inputs { + return new CheckBalancesCall__Inputs(this); + } + + get outputs(): CheckBalancesCall__Outputs { + return new CheckBalancesCall__Outputs(this); + } +} + +export class CheckBalancesCall__Inputs { + _call: CheckBalancesCall; + + constructor(call: CheckBalancesCall) { + this._call = call; + } + + get _borrowerAddress(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get _collateralInfo(): Array { + return this._call.inputValues[1].value.toTupleArray< + CheckBalancesCall_collateralInfoStruct + >(); + } +} + +export class CheckBalancesCall__Outputs { + _call: CheckBalancesCall; + + constructor(call: CheckBalancesCall) { + this._call = call; + } + + get validated_(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } + + get checks_(): Array { + return this._call.outputValues[1].value.toBooleanArray(); + } +} + +export class CheckBalancesCall_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CommitCollateralCall extends ethereum.Call { + get inputs(): CommitCollateralCall__Inputs { + return new CommitCollateralCall__Inputs(this); + } + + get outputs(): CommitCollateralCall__Outputs { + return new CommitCollateralCall__Outputs(this); + } +} + +export class CommitCollateralCall__Inputs { + _call: CommitCollateralCall; + + constructor(call: CommitCollateralCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _collateralInfo(): Array { + return this._call.inputValues[1].value.toTupleArray< + CommitCollateralCall_collateralInfoStruct + >(); + } +} + +export class CommitCollateralCall__Outputs { + _call: CommitCollateralCall; + + constructor(call: CommitCollateralCall) { + this._call = call; + } + + get validation_(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class CommitCollateralCall_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class CommitCollateral1Call extends ethereum.Call { + get inputs(): CommitCollateral1Call__Inputs { + return new CommitCollateral1Call__Inputs(this); + } + + get outputs(): CommitCollateral1Call__Outputs { + return new CommitCollateral1Call__Outputs(this); + } +} + +export class CommitCollateral1Call__Inputs { + _call: CommitCollateral1Call; + + constructor(call: CommitCollateral1Call) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _collateralInfo(): CommitCollateral1Call_collateralInfoStruct { + return changetype( + this._call.inputValues[1].value.toTuple() + ); + } +} + +export class CommitCollateral1Call__Outputs { + _call: CommitCollateral1Call; + + constructor(call: CommitCollateral1Call) { + this._call = call; + } + + get validation_(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class CommitCollateral1Call_collateralInfoStruct extends ethereum.Tuple { + get _collateralType(): i32 { + return this[0].toI32(); + } + + get _amount(): BigInt { + return this[1].toBigInt(); + } + + get _tokenId(): BigInt { + return this[2].toBigInt(); + } + + get _collateralAddress(): Address { + return this[3].toAddress(); + } +} + +export class DeployAndDepositCall extends ethereum.Call { + get inputs(): DeployAndDepositCall__Inputs { + return new DeployAndDepositCall__Inputs(this); + } + + get outputs(): DeployAndDepositCall__Outputs { + return new DeployAndDepositCall__Outputs(this); + } +} + +export class DeployAndDepositCall__Inputs { + _call: DeployAndDepositCall; + + constructor(call: DeployAndDepositCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class DeployAndDepositCall__Outputs { + _call: DeployAndDepositCall; + + constructor(call: DeployAndDepositCall) { + this._call = call; + } +} + +export class InitializeCall extends ethereum.Call { + get inputs(): InitializeCall__Inputs { + return new InitializeCall__Inputs(this); + } + + get outputs(): InitializeCall__Outputs { + return new InitializeCall__Outputs(this); + } +} + +export class InitializeCall__Inputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } + + get _collateralEscrowBeacon(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get _tellerV2(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class InitializeCall__Outputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } +} + +export class IsBidCollateralBackedCall extends ethereum.Call { + get inputs(): IsBidCollateralBackedCall__Inputs { + return new IsBidCollateralBackedCall__Inputs(this); + } + + get outputs(): IsBidCollateralBackedCall__Outputs { + return new IsBidCollateralBackedCall__Outputs(this); + } +} + +export class IsBidCollateralBackedCall__Inputs { + _call: IsBidCollateralBackedCall; + + constructor(call: IsBidCollateralBackedCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class IsBidCollateralBackedCall__Outputs { + _call: IsBidCollateralBackedCall; + + constructor(call: IsBidCollateralBackedCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class LenderClaimCollateralCall extends ethereum.Call { + get inputs(): LenderClaimCollateralCall__Inputs { + return new LenderClaimCollateralCall__Inputs(this); + } + + get outputs(): LenderClaimCollateralCall__Outputs { + return new LenderClaimCollateralCall__Outputs(this); + } +} + +export class LenderClaimCollateralCall__Inputs { + _call: LenderClaimCollateralCall; + + constructor(call: LenderClaimCollateralCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class LenderClaimCollateralCall__Outputs { + _call: LenderClaimCollateralCall; + + constructor(call: LenderClaimCollateralCall) { + this._call = call; + } +} + +export class LenderClaimCollateralWithRecipientCall extends ethereum.Call { + get inputs(): LenderClaimCollateralWithRecipientCall__Inputs { + return new LenderClaimCollateralWithRecipientCall__Inputs(this); + } + + get outputs(): LenderClaimCollateralWithRecipientCall__Outputs { + return new LenderClaimCollateralWithRecipientCall__Outputs(this); + } +} + +export class LenderClaimCollateralWithRecipientCall__Inputs { + _call: LenderClaimCollateralWithRecipientCall; + + constructor(call: LenderClaimCollateralWithRecipientCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _collateralRecipient(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class LenderClaimCollateralWithRecipientCall__Outputs { + _call: LenderClaimCollateralWithRecipientCall; + + constructor(call: LenderClaimCollateralWithRecipientCall) { + this._call = call; + } +} + +export class LiquidateCollateralCall extends ethereum.Call { + get inputs(): LiquidateCollateralCall__Inputs { + return new LiquidateCollateralCall__Inputs(this); + } + + get outputs(): LiquidateCollateralCall__Outputs { + return new LiquidateCollateralCall__Outputs(this); + } +} + +export class LiquidateCollateralCall__Inputs { + _call: LiquidateCollateralCall; + + constructor(call: LiquidateCollateralCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _liquidatorAddress(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class LiquidateCollateralCall__Outputs { + _call: LiquidateCollateralCall; + + constructor(call: LiquidateCollateralCall) { + this._call = call; + } +} + +export class OnERC1155BatchReceivedCall extends ethereum.Call { + get inputs(): OnERC1155BatchReceivedCall__Inputs { + return new OnERC1155BatchReceivedCall__Inputs(this); + } + + get outputs(): OnERC1155BatchReceivedCall__Outputs { + return new OnERC1155BatchReceivedCall__Outputs(this); + } +} + +export class OnERC1155BatchReceivedCall__Inputs { + _call: OnERC1155BatchReceivedCall; + + constructor(call: OnERC1155BatchReceivedCall) { + this._call = call; + } + + get value0(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get value1(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get _ids(): Array { + return this._call.inputValues[2].value.toBigIntArray(); + } + + get _values(): Array { + return this._call.inputValues[3].value.toBigIntArray(); + } + + get value4(): Bytes { + return this._call.inputValues[4].value.toBytes(); + } +} + +export class OnERC1155BatchReceivedCall__Outputs { + _call: OnERC1155BatchReceivedCall; + + constructor(call: OnERC1155BatchReceivedCall) { + this._call = call; + } + + get value0(): Bytes { + return this._call.outputValues[0].value.toBytes(); + } +} + +export class OnERC1155ReceivedCall extends ethereum.Call { + get inputs(): OnERC1155ReceivedCall__Inputs { + return new OnERC1155ReceivedCall__Inputs(this); + } + + get outputs(): OnERC1155ReceivedCall__Outputs { + return new OnERC1155ReceivedCall__Outputs(this); + } +} + +export class OnERC1155ReceivedCall__Inputs { + _call: OnERC1155ReceivedCall; + + constructor(call: OnERC1155ReceivedCall) { + this._call = call; + } + + get value0(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get value1(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get id(): BigInt { + return this._call.inputValues[2].value.toBigInt(); + } + + get value(): BigInt { + return this._call.inputValues[3].value.toBigInt(); + } + + get value4(): Bytes { + return this._call.inputValues[4].value.toBytes(); + } +} + +export class OnERC1155ReceivedCall__Outputs { + _call: OnERC1155ReceivedCall; + + constructor(call: OnERC1155ReceivedCall) { + this._call = call; + } + + get value0(): Bytes { + return this._call.outputValues[0].value.toBytes(); + } +} + +export class RenounceOwnershipCall extends ethereum.Call { + get inputs(): RenounceOwnershipCall__Inputs { + return new RenounceOwnershipCall__Inputs(this); + } + + get outputs(): RenounceOwnershipCall__Outputs { + return new RenounceOwnershipCall__Outputs(this); + } +} + +export class RenounceOwnershipCall__Inputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall__Outputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RevalidateCollateralCall extends ethereum.Call { + get inputs(): RevalidateCollateralCall__Inputs { + return new RevalidateCollateralCall__Inputs(this); + } + + get outputs(): RevalidateCollateralCall__Outputs { + return new RevalidateCollateralCall__Outputs(this); + } +} + +export class RevalidateCollateralCall__Inputs { + _call: RevalidateCollateralCall; + + constructor(call: RevalidateCollateralCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class RevalidateCollateralCall__Outputs { + _call: RevalidateCollateralCall; + + constructor(call: RevalidateCollateralCall) { + this._call = call; + } + + get validation_(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class SetCollateralEscrowBeaconCall extends ethereum.Call { + get inputs(): SetCollateralEscrowBeaconCall__Inputs { + return new SetCollateralEscrowBeaconCall__Inputs(this); + } + + get outputs(): SetCollateralEscrowBeaconCall__Outputs { + return new SetCollateralEscrowBeaconCall__Outputs(this); + } +} + +export class SetCollateralEscrowBeaconCall__Inputs { + _call: SetCollateralEscrowBeaconCall; + + constructor(call: SetCollateralEscrowBeaconCall) { + this._call = call; + } + + get _collateralEscrowBeacon(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class SetCollateralEscrowBeaconCall__Outputs { + _call: SetCollateralEscrowBeaconCall; + + constructor(call: SetCollateralEscrowBeaconCall) { + this._call = call; + } +} + +export class TransferOwnershipCall extends ethereum.Call { + get inputs(): TransferOwnershipCall__Inputs { + return new TransferOwnershipCall__Inputs(this); + } + + get outputs(): TransferOwnershipCall__Outputs { + return new TransferOwnershipCall__Outputs(this); + } +} + +export class TransferOwnershipCall__Inputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } + + get newOwner(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class TransferOwnershipCall__Outputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } +} + +export class WithdrawCall extends ethereum.Call { + get inputs(): WithdrawCall__Inputs { + return new WithdrawCall__Inputs(this); + } + + get outputs(): WithdrawCall__Outputs { + return new WithdrawCall__Outputs(this); + } +} + +export class WithdrawCall__Inputs { + _call: WithdrawCall; + + constructor(call: WithdrawCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class WithdrawCall__Outputs { + _call: WithdrawCall; + + constructor(call: WithdrawCall) { + this._call = call; + } +} + +export class WithdrawDustTokensCall extends ethereum.Call { + get inputs(): WithdrawDustTokensCall__Inputs { + return new WithdrawDustTokensCall__Inputs(this); + } + + get outputs(): WithdrawDustTokensCall__Outputs { + return new WithdrawDustTokensCall__Outputs(this); + } +} + +export class WithdrawDustTokensCall__Inputs { + _call: WithdrawDustTokensCall; + + constructor(call: WithdrawDustTokensCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _tokenAddress(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get _amount(): BigInt { + return this._call.inputValues[2].value.toBigInt(); + } + + get _recipientAddress(): Address { + return this._call.inputValues[3].value.toAddress(); + } +} + +export class WithdrawDustTokensCall__Outputs { + _call: WithdrawDustTokensCall; + + constructor(call: WithdrawDustTokensCall) { + this._call = call; + } +} diff --git a/packages/subgraph-pool-v3/generated/Factory/Factory.ts b/packages/subgraph-pool-v3/generated/Factory/Factory.ts new file mode 100644 index 000000000..f04fc8e23 --- /dev/null +++ b/packages/subgraph-pool-v3/generated/Factory/Factory.ts @@ -0,0 +1,383 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + ethereum, + JSONValue, + TypedMap, + Entity, + Bytes, + Address, + BigInt +} from "@graphprotocol/graph-ts"; + +export class DeployedLenderGroupContract extends ethereum.Event { + get params(): DeployedLenderGroupContract__Params { + return new DeployedLenderGroupContract__Params(this); + } +} + +export class DeployedLenderGroupContract__Params { + _event: DeployedLenderGroupContract; + + constructor(event: DeployedLenderGroupContract) { + this._event = event; + } + + get groupContract(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class Initialized extends ethereum.Event { + get params(): Initialized__Params { + return new Initialized__Params(this); + } +} + +export class Initialized__Params { + _event: Initialized; + + constructor(event: Initialized) { + this._event = event; + } + + get version(): i32 { + return this._event.parameters[0].value.toI32(); + } +} + +export class OwnershipTransferred extends ethereum.Event { + get params(): OwnershipTransferred__Params { + return new OwnershipTransferred__Params(this); + } +} + +export class OwnershipTransferred__Params { + _event: OwnershipTransferred; + + constructor(event: OwnershipTransferred) { + this._event = event; + } + + get previousOwner(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get newOwner(): Address { + return this._event.parameters[1].value.toAddress(); + } +} + +export class Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct extends ethereum.Tuple { + get principalTokenAddress(): Address { + return this[0].toAddress(); + } + + get collateralTokenAddress(): Address { + return this[1].toAddress(); + } + + get marketId(): BigInt { + return this[2].toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this[3].toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this[4].toI32(); + } + + get interestRateUpperBound(): i32 { + return this[5].toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this[6].toI32(); + } + + get collateralRatio(): i32 { + return this[7].toI32(); + } +} + +export class Factory extends ethereum.SmartContract { + static bind(address: Address): Factory { + return new Factory("Factory", address); + } + + deployLenderCommitmentGroupPool( + _initialPrincipalAmount: BigInt, + _commitmentGroupConfig: Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct, + _priceAdapterAddress: Address, + _priceAdapterRoute: Bytes + ): Address { + let result = super.call( + "deployLenderCommitmentGroupPool", + "deployLenderCommitmentGroupPool(uint256,(address,address,uint256,uint32,uint16,uint16,uint16,uint16),address,bytes):(address)", + [ + ethereum.Value.fromUnsignedBigInt(_initialPrincipalAmount), + ethereum.Value.fromTuple(_commitmentGroupConfig), + ethereum.Value.fromAddress(_priceAdapterAddress), + ethereum.Value.fromBytes(_priceAdapterRoute) + ] + ); + + return result[0].toAddress(); + } + + try_deployLenderCommitmentGroupPool( + _initialPrincipalAmount: BigInt, + _commitmentGroupConfig: Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct, + _priceAdapterAddress: Address, + _priceAdapterRoute: Bytes + ): ethereum.CallResult
{ + let result = super.tryCall( + "deployLenderCommitmentGroupPool", + "deployLenderCommitmentGroupPool(uint256,(address,address,uint256,uint32,uint16,uint16,uint16,uint16),address,bytes):(address)", + [ + ethereum.Value.fromUnsignedBigInt(_initialPrincipalAmount), + ethereum.Value.fromTuple(_commitmentGroupConfig), + ethereum.Value.fromAddress(_priceAdapterAddress), + ethereum.Value.fromBytes(_priceAdapterRoute) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + deployedLenderGroupContracts(param0: Address): BigInt { + let result = super.call( + "deployedLenderGroupContracts", + "deployedLenderGroupContracts(address):(uint256)", + [ethereum.Value.fromAddress(param0)] + ); + + return result[0].toBigInt(); + } + + try_deployedLenderGroupContracts( + param0: Address + ): ethereum.CallResult { + let result = super.tryCall( + "deployedLenderGroupContracts", + "deployedLenderGroupContracts(address):(uint256)", + [ethereum.Value.fromAddress(param0)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + lenderGroupBeacon(): Address { + let result = super.call( + "lenderGroupBeacon", + "lenderGroupBeacon():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_lenderGroupBeacon(): ethereum.CallResult
{ + let result = super.tryCall( + "lenderGroupBeacon", + "lenderGroupBeacon():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + owner(): Address { + let result = super.call("owner", "owner():(address)", []); + + return result[0].toAddress(); + } + + try_owner(): ethereum.CallResult
{ + let result = super.tryCall("owner", "owner():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } +} + +export class DeployLenderCommitmentGroupPoolCall extends ethereum.Call { + get inputs(): DeployLenderCommitmentGroupPoolCall__Inputs { + return new DeployLenderCommitmentGroupPoolCall__Inputs(this); + } + + get outputs(): DeployLenderCommitmentGroupPoolCall__Outputs { + return new DeployLenderCommitmentGroupPoolCall__Outputs(this); + } +} + +export class DeployLenderCommitmentGroupPoolCall__Inputs { + _call: DeployLenderCommitmentGroupPoolCall; + + constructor(call: DeployLenderCommitmentGroupPoolCall) { + this._call = call; + } + + get _initialPrincipalAmount(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _commitmentGroupConfig(): DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct { + return changetype< + DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct + >(this._call.inputValues[1].value.toTuple()); + } + + get _priceAdapterAddress(): Address { + return this._call.inputValues[2].value.toAddress(); + } + + get _priceAdapterRoute(): Bytes { + return this._call.inputValues[3].value.toBytes(); + } +} + +export class DeployLenderCommitmentGroupPoolCall__Outputs { + _call: DeployLenderCommitmentGroupPoolCall; + + constructor(call: DeployLenderCommitmentGroupPoolCall) { + this._call = call; + } + + get value0(): Address { + return this._call.outputValues[0].value.toAddress(); + } +} + +export class DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct extends ethereum.Tuple { + get principalTokenAddress(): Address { + return this[0].toAddress(); + } + + get collateralTokenAddress(): Address { + return this[1].toAddress(); + } + + get marketId(): BigInt { + return this[2].toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this[3].toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this[4].toI32(); + } + + get interestRateUpperBound(): i32 { + return this[5].toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this[6].toI32(); + } + + get collateralRatio(): i32 { + return this[7].toI32(); + } +} + +export class InitializeCall extends ethereum.Call { + get inputs(): InitializeCall__Inputs { + return new InitializeCall__Inputs(this); + } + + get outputs(): InitializeCall__Outputs { + return new InitializeCall__Outputs(this); + } +} + +export class InitializeCall__Inputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } + + get _lenderGroupBeacon(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class InitializeCall__Outputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall extends ethereum.Call { + get inputs(): RenounceOwnershipCall__Inputs { + return new RenounceOwnershipCall__Inputs(this); + } + + get outputs(): RenounceOwnershipCall__Outputs { + return new RenounceOwnershipCall__Outputs(this); + } +} + +export class RenounceOwnershipCall__Inputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall__Outputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class TransferOwnershipCall extends ethereum.Call { + get inputs(): TransferOwnershipCall__Inputs { + return new TransferOwnershipCall__Inputs(this); + } + + get outputs(): TransferOwnershipCall__Outputs { + return new TransferOwnershipCall__Outputs(this); + } +} + +export class TransferOwnershipCall__Inputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } + + get newOwner(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class TransferOwnershipCall__Outputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } +} diff --git a/packages/subgraph-pool-v3/generated/schema.ts b/packages/subgraph-pool-v3/generated/schema.ts new file mode 100644 index 000000000..266afcfd5 --- /dev/null +++ b/packages/subgraph-pool-v3/generated/schema.ts @@ -0,0 +1,3334 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + TypedMap, + Entity, + Value, + ValueKind, + store, + Bytes, + BigInt, + BigDecimal +} from "@graphprotocol/graph-ts"; + +export class factory_admin_changed extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save factory_admin_changed entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type factory_admin_changed must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("factory_admin_changed", id.toString(), this); + } + } + + static loadInBlock(id: string): factory_admin_changed | null { + return changetype( + store.get_in_block("factory_admin_changed", id) + ); + } + + static load(id: string): factory_admin_changed | null { + return changetype( + store.get("factory_admin_changed", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get new_admin(): Bytes { + let value = this.get("new_admin"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set new_admin(value: Bytes) { + this.set("new_admin", Value.fromBytes(value)); + } + + get previous_admin(): Bytes { + let value = this.get("previous_admin"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set previous_admin(value: Bytes) { + this.set("previous_admin", Value.fromBytes(value)); + } +} + +export class factory_beacon_upgraded extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save factory_beacon_upgraded entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type factory_beacon_upgraded must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("factory_beacon_upgraded", id.toString(), this); + } + } + + static loadInBlock(id: string): factory_beacon_upgraded | null { + return changetype( + store.get_in_block("factory_beacon_upgraded", id) + ); + } + + static load(id: string): factory_beacon_upgraded | null { + return changetype( + store.get("factory_beacon_upgraded", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get beacon(): Bytes { + let value = this.get("beacon"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set beacon(value: Bytes) { + this.set("beacon", Value.fromBytes(value)); + } +} + +export class factory_deployed_lender_group_contract extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save factory_deployed_lender_group_contract entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type factory_deployed_lender_group_contract must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("factory_deployed_lender_group_contract", id.toString(), this); + } + } + + static loadInBlock( + id: string + ): factory_deployed_lender_group_contract | null { + return changetype( + store.get_in_block("factory_deployed_lender_group_contract", id) + ); + } + + static load(id: string): factory_deployed_lender_group_contract | null { + return changetype( + store.get("factory_deployed_lender_group_contract", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_contract(): Bytes { + let value = this.get("group_contract"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_contract(value: Bytes) { + this.set("group_contract", Value.fromBytes(value)); + } +} + +export class factory_upgraded extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save factory_upgraded entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type factory_upgraded must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("factory_upgraded", id.toString(), this); + } + } + + static loadInBlock(id: string): factory_upgraded | null { + return changetype( + store.get_in_block("factory_upgraded", id) + ); + } + + static load(id: string): factory_upgraded | null { + return changetype( + store.get("factory_upgraded", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get implementation(): Bytes { + let value = this.get("implementation"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set implementation(value: Bytes) { + this.set("implementation", Value.fromBytes(value)); + } +} + +export class group_borrower_accepted_funds extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_borrower_accepted_funds entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_borrower_accepted_funds must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_borrower_accepted_funds", id.toString(), this); + } + } + + static loadInBlock(id: string): group_borrower_accepted_funds | null { + return changetype( + store.get_in_block("group_borrower_accepted_funds", id) + ); + } + + static load(id: string): group_borrower_accepted_funds | null { + return changetype( + store.get("group_borrower_accepted_funds", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get bid_id(): BigInt { + let value = this.get("bid_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set bid_id(value: BigInt) { + this.set("bid_id", Value.fromBigInt(value)); + } + + get borrower(): Bytes { + let value = this.get("borrower"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set borrower(value: Bytes) { + this.set("borrower", Value.fromBytes(value)); + } + + get collateral_amount(): BigInt { + let value = this.get("collateral_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set collateral_amount(value: BigInt) { + this.set("collateral_amount", Value.fromBigInt(value)); + } + + get interest_rate(): BigInt { + let value = this.get("interest_rate"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_rate(value: BigInt) { + this.set("interest_rate", Value.fromBigInt(value)); + } + + get loan_duration(): BigInt { + let value = this.get("loan_duration"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set loan_duration(value: BigInt) { + this.set("loan_duration", Value.fromBigInt(value)); + } + + get principal_amount(): BigInt { + let value = this.get("principal_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set principal_amount(value: BigInt) { + this.set("principal_amount", Value.fromBigInt(value)); + } +} + +export class group_lender_added_principal extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_lender_added_principal entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_lender_added_principal must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_lender_added_principal", id.toString(), this); + } + } + + static loadInBlock(id: string): group_lender_added_principal | null { + return changetype( + store.get_in_block("group_lender_added_principal", id) + ); + } + + static load(id: string): group_lender_added_principal | null { + return changetype( + store.get("group_lender_added_principal", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get amount(): BigInt { + let value = this.get("amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set amount(value: BigInt) { + this.set("amount", Value.fromBigInt(value)); + } + + get lender(): Bytes { + let value = this.get("lender"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set lender(value: Bytes) { + this.set("lender", Value.fromBytes(value)); + } + + get shares_amount(): BigInt { + let value = this.get("shares_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set shares_amount(value: BigInt) { + this.set("shares_amount", Value.fromBigInt(value)); + } + + get shares_recipient(): Bytes { + let value = this.get("shares_recipient"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set shares_recipient(value: Bytes) { + this.set("shares_recipient", Value.fromBytes(value)); + } +} + +export class group_earnings_withdrawn extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_earnings_withdrawn entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_earnings_withdrawn must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_earnings_withdrawn", id.toString(), this); + } + } + + static loadInBlock(id: string): group_earnings_withdrawn | null { + return changetype( + store.get_in_block("group_earnings_withdrawn", id) + ); + } + + static load(id: string): group_earnings_withdrawn | null { + return changetype( + store.get("group_earnings_withdrawn", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get amount_pool_shares_tokens(): BigInt { + let value = this.get("amount_pool_shares_tokens"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set amount_pool_shares_tokens(value: BigInt) { + this.set("amount_pool_shares_tokens", Value.fromBigInt(value)); + } + + get lender(): Bytes { + let value = this.get("lender"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set lender(value: Bytes) { + this.set("lender", Value.fromBytes(value)); + } + + get principal_tokens_withdrawn(): BigInt { + let value = this.get("principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set principal_tokens_withdrawn(value: BigInt) { + this.set("principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get recipient(): Bytes { + let value = this.get("recipient"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set recipient(value: Bytes) { + this.set("recipient", Value.fromBytes(value)); + } +} + +export class group_defaulted_loan_liquidated extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_defaulted_loan_liquidated entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_defaulted_loan_liquidated must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_defaulted_loan_liquidated", id.toString(), this); + } + } + + static loadInBlock(id: string): group_defaulted_loan_liquidated | null { + return changetype( + store.get_in_block("group_defaulted_loan_liquidated", id) + ); + } + + static load(id: string): group_defaulted_loan_liquidated | null { + return changetype( + store.get("group_defaulted_loan_liquidated", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get amount_due(): BigInt { + let value = this.get("amount_due"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set amount_due(value: BigInt) { + this.set("amount_due", Value.fromBigInt(value)); + } + + get bid_id(): BigInt { + let value = this.get("bid_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set bid_id(value: BigInt) { + this.set("bid_id", Value.fromBigInt(value)); + } + + get liquidator(): Bytes { + let value = this.get("liquidator"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set liquidator(value: Bytes) { + this.set("liquidator", Value.fromBytes(value)); + } + + get token_amount_difference(): BigInt { + let value = this.get("token_amount_difference"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set token_amount_difference(value: BigInt) { + this.set("token_amount_difference", Value.fromBigInt(value)); + } +} + +export class group_initialized extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_initialized entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_initialized must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_initialized", id.toString(), this); + } + } + + static loadInBlock(id: string): group_initialized | null { + return changetype( + store.get_in_block("group_initialized", id) + ); + } + + static load(id: string): group_initialized | null { + return changetype( + store.get("group_initialized", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get version(): BigInt { + let value = this.get("version"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set version(value: BigInt) { + this.set("version", Value.fromBigInt(value)); + } +} + +export class group_loan_repaid extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_loan_repaid entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_loan_repaid must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_loan_repaid", id.toString(), this); + } + } + + static loadInBlock(id: string): group_loan_repaid | null { + return changetype( + store.get_in_block("group_loan_repaid", id) + ); + } + + static load(id: string): group_loan_repaid | null { + return changetype( + store.get("group_loan_repaid", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get bid_id(): BigInt { + let value = this.get("bid_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set bid_id(value: BigInt) { + this.set("bid_id", Value.fromBigInt(value)); + } + + get interest_amount(): BigInt { + let value = this.get("interest_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_amount(value: BigInt) { + this.set("interest_amount", Value.fromBigInt(value)); + } + + get principal_amount(): BigInt { + let value = this.get("principal_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set principal_amount(value: BigInt) { + this.set("principal_amount", Value.fromBigInt(value)); + } + + get repayer(): Bytes { + let value = this.get("repayer"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set repayer(value: Bytes) { + this.set("repayer", Value.fromBytes(value)); + } + + get total_interest_collected(): BigInt { + let value = this.get("total_interest_collected"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_interest_collected(value: BigInt) { + this.set("total_interest_collected", Value.fromBigInt(value)); + } + + get total_principal_repaid(): BigInt { + let value = this.get("total_principal_repaid"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_repaid(value: BigInt) { + this.set("total_principal_repaid", Value.fromBigInt(value)); + } +} + +export class group_ownership_transferred extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_ownership_transferred entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_ownership_transferred must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_ownership_transferred", id.toString(), this); + } + } + + static loadInBlock(id: string): group_ownership_transferred | null { + return changetype( + store.get_in_block("group_ownership_transferred", id) + ); + } + + static load(id: string): group_ownership_transferred | null { + return changetype( + store.get("group_ownership_transferred", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get new_owner(): Bytes { + let value = this.get("new_owner"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set new_owner(value: Bytes) { + this.set("new_owner", Value.fromBytes(value)); + } + + get previous_owner(): Bytes { + let value = this.get("previous_owner"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set previous_owner(value: Bytes) { + this.set("previous_owner", Value.fromBytes(value)); + } +} + +export class group_paused extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_paused entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_paused must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_paused", id.toString(), this); + } + } + + static loadInBlock(id: string): group_paused | null { + return changetype( + store.get_in_block("group_paused", id) + ); + } + + static load(id: string): group_paused | null { + return changetype(store.get("group_paused", id)); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get account(): Bytes { + let value = this.get("account"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set account(value: Bytes) { + this.set("account", Value.fromBytes(value)); + } +} + +export class group_pool_initialized extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_pool_initialized entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_initialized must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_initialized", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_initialized | null { + return changetype( + store.get_in_block("group_pool_initialized", id) + ); + } + + static load(id: string): group_pool_initialized | null { + return changetype( + store.get("group_pool_initialized", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get collateral_token_address(): Bytes { + let value = this.get("collateral_token_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set collateral_token_address(value: Bytes) { + this.set("collateral_token_address", Value.fromBytes(value)); + } + + get interest_rate_lower_bound(): BigInt { + let value = this.get("interest_rate_lower_bound"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_rate_lower_bound(value: BigInt) { + this.set("interest_rate_lower_bound", Value.fromBigInt(value)); + } + + get interest_rate_upper_bound(): BigInt { + let value = this.get("interest_rate_upper_bound"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_rate_upper_bound(value: BigInt) { + this.set("interest_rate_upper_bound", Value.fromBigInt(value)); + } + + get liquidity_threshold_percent(): BigInt { + let value = this.get("liquidity_threshold_percent"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set liquidity_threshold_percent(value: BigInt) { + this.set("liquidity_threshold_percent", Value.fromBigInt(value)); + } + + get loan_to_value_percent(): BigInt { + let value = this.get("loan_to_value_percent"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set loan_to_value_percent(value: BigInt) { + this.set("loan_to_value_percent", Value.fromBigInt(value)); + } + + get market_id(): BigInt { + let value = this.get("market_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set market_id(value: BigInt) { + this.set("market_id", Value.fromBigInt(value)); + } + + get max_loan_duration(): BigInt { + let value = this.get("max_loan_duration"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set max_loan_duration(value: BigInt) { + this.set("max_loan_duration", Value.fromBigInt(value)); + } + + get pool_shares_token(): Bytes { + let value = this.get("pool_shares_token"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set pool_shares_token(value: Bytes) { + this.set("pool_shares_token", Value.fromBytes(value)); + } + + get principal_token_address(): Bytes { + let value = this.get("principal_token_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set principal_token_address(value: Bytes) { + this.set("principal_token_address", Value.fromBytes(value)); + } +} + +export class group_unpaused extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_unpaused entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_unpaused must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_unpaused", id.toString(), this); + } + } + + static loadInBlock(id: string): group_unpaused | null { + return changetype( + store.get_in_block("group_unpaused", id) + ); + } + + static load(id: string): group_unpaused | null { + return changetype(store.get("group_unpaused", id)); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get evt_tx_hash(): Bytes { + let value = this.get("evt_tx_hash"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set evt_tx_hash(value: Bytes) { + this.set("evt_tx_hash", Value.fromBytes(value)); + } + + get evt_index(): BigInt { + let value = this.get("evt_index"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_index(value: BigInt) { + this.set("evt_index", Value.fromBigInt(value)); + } + + get evt_block_time(): BigInt { + let value = this.get("evt_block_time"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_time(value: BigInt) { + this.set("evt_block_time", Value.fromBigInt(value)); + } + + get evt_block_number(): BigInt { + let value = this.get("evt_block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set evt_block_number(value: BigInt) { + this.set("evt_block_number", Value.fromBigInt(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get account(): Bytes { + let value = this.get("account"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set account(value: Bytes) { + this.set("account", Value.fromBytes(value)); + } +} + +export class group_pool_bid extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_pool_bid entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_bid must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_bid", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_bid | null { + return changetype( + store.get_in_block("group_pool_bid", id) + ); + } + + static load(id: string): group_pool_bid | null { + return changetype(store.get("group_pool_bid", id)); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get bid_id(): BigInt { + let value = this.get("bid_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set bid_id(value: BigInt) { + this.set("bid_id", Value.fromBigInt(value)); + } + + get borrower(): Bytes { + let value = this.get("borrower"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set borrower(value: Bytes) { + this.set("borrower", Value.fromBytes(value)); + } + + get collateral_amount(): BigInt { + let value = this.get("collateral_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set collateral_amount(value: BigInt) { + this.set("collateral_amount", Value.fromBigInt(value)); + } + + get principal_amount(): BigInt { + let value = this.get("principal_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set principal_amount(value: BigInt) { + this.set("principal_amount", Value.fromBigInt(value)); + } +} + +export class teller_bid extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save teller_bid entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type teller_bid must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("teller_bid", id.toString(), this); + } + } + + static loadInBlock(id: string): teller_bid | null { + return changetype(store.get_in_block("teller_bid", id)); + } + + static load(id: string): teller_bid | null { + return changetype(store.get("teller_bid", id)); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get bid_id(): BigInt { + let value = this.get("bid_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set bid_id(value: BigInt) { + this.set("bid_id", Value.fromBigInt(value)); + } + + get borrower(): Bytes { + let value = this.get("borrower"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set borrower(value: Bytes) { + this.set("borrower", Value.fromBytes(value)); + } + + get collateral_amount(): BigInt { + let value = this.get("collateral_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set collateral_amount(value: BigInt) { + this.set("collateral_amount", Value.fromBigInt(value)); + } + + get principal_amount(): BigInt { + let value = this.get("principal_amount"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set principal_amount(value: BigInt) { + this.set("principal_amount", Value.fromBigInt(value)); + } +} + +export class group_pool_metric extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_pool_metric entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_metric must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_metric", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_metric | null { + return changetype( + store.get_in_block("group_pool_metric", id) + ); + } + + static load(id: string): group_pool_metric | null { + return changetype( + store.get("group_pool_metric", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get created_at(): BigInt { + let value = this.get("created_at"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set created_at(value: BigInt) { + this.set("created_at", Value.fromBigInt(value)); + } + + get principal_token_address(): Bytes { + let value = this.get("principal_token_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set principal_token_address(value: Bytes) { + this.set("principal_token_address", Value.fromBytes(value)); + } + + get collateral_token_address(): Bytes { + let value = this.get("collateral_token_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set collateral_token_address(value: Bytes) { + this.set("collateral_token_address", Value.fromBytes(value)); + } + + get shares_token_address(): Bytes { + let value = this.get("shares_token_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set shares_token_address(value: Bytes) { + this.set("shares_token_address", Value.fromBytes(value)); + } + + get teller_v2_address(): Bytes { + let value = this.get("teller_v2_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set teller_v2_address(value: Bytes) { + this.set("teller_v2_address", Value.fromBytes(value)); + } + + get smart_commitment_forwarder_address(): Bytes { + let value = this.get("smart_commitment_forwarder_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set smart_commitment_forwarder_address(value: Bytes) { + this.set("smart_commitment_forwarder_address", Value.fromBytes(value)); + } + + get market_id(): BigInt { + let value = this.get("market_id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set market_id(value: BigInt) { + this.set("market_id", Value.fromBigInt(value)); + } + + get max_loan_duration(): BigInt { + let value = this.get("max_loan_duration"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set max_loan_duration(value: BigInt) { + this.set("max_loan_duration", Value.fromBigInt(value)); + } + + get interest_rate_upper_bound(): BigInt { + let value = this.get("interest_rate_upper_bound"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_rate_upper_bound(value: BigInt) { + this.set("interest_rate_upper_bound", Value.fromBigInt(value)); + } + + get interest_rate_lower_bound(): BigInt { + let value = this.get("interest_rate_lower_bound"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set interest_rate_lower_bound(value: BigInt) { + this.set("interest_rate_lower_bound", Value.fromBigInt(value)); + } + + get current_min_interest_rate(): BigInt { + let value = this.get("current_min_interest_rate"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set current_min_interest_rate(value: BigInt) { + this.set("current_min_interest_rate", Value.fromBigInt(value)); + } + + get liquidity_threshold_percent(): BigInt { + let value = this.get("liquidity_threshold_percent"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set liquidity_threshold_percent(value: BigInt) { + this.set("liquidity_threshold_percent", Value.fromBigInt(value)); + } + + get collateral_ratio(): BigInt { + let value = this.get("collateral_ratio"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set collateral_ratio(value: BigInt) { + this.set("collateral_ratio", Value.fromBigInt(value)); + } + + get total_principal_tokens_committed(): BigInt { + let value = this.get("total_principal_tokens_committed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_committed(value: BigInt) { + this.set("total_principal_tokens_committed", Value.fromBigInt(value)); + } + + get total_principal_tokens_withdrawn(): BigInt { + let value = this.get("total_principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_withdrawn(value: BigInt) { + this.set("total_principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_borrowed(): BigInt { + let value = this.get("total_principal_tokens_borrowed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_borrowed(value: BigInt) { + this.set("total_principal_tokens_borrowed", Value.fromBigInt(value)); + } + + get total_collateral_tokens_deposited(): BigInt { + let value = this.get("total_collateral_tokens_deposited"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_deposited(value: BigInt) { + this.set("total_collateral_tokens_deposited", Value.fromBigInt(value)); + } + + get total_collateral_tokens_withdrawn(): BigInt { + let value = this.get("total_collateral_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_withdrawn(value: BigInt) { + this.set("total_collateral_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_repaid(): BigInt { + let value = this.get("total_principal_tokens_repaid"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_repaid(value: BigInt) { + this.set("total_principal_tokens_repaid", Value.fromBigInt(value)); + } + + get total_principal_tokens_repaid_by_liquidation_auction(): BigInt { + let value = this.get( + "total_principal_tokens_repaid_by_liquidation_auction" + ); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_repaid_by_liquidation_auction(value: BigInt) { + this.set( + "total_principal_tokens_repaid_by_liquidation_auction", + Value.fromBigInt(value) + ); + } + + get total_interest_collected(): BigInt { + let value = this.get("total_interest_collected"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_interest_collected(value: BigInt) { + this.set("total_interest_collected", Value.fromBigInt(value)); + } + + get token_difference_from_liquidations(): BigInt { + let value = this.get("token_difference_from_liquidations"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set token_difference_from_liquidations(value: BigInt) { + this.set("token_difference_from_liquidations", Value.fromBigInt(value)); + } +} + +export class group_pool_metric_data_point extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_pool_metric_data_point entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_metric_data_point must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_metric_data_point", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_metric_data_point | null { + return changetype( + store.get_in_block("group_pool_metric_data_point", id) + ); + } + + static load(id: string): group_pool_metric_data_point | null { + return changetype( + store.get("group_pool_metric_data_point", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get block_number(): BigInt { + let value = this.get("block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set block_number(value: BigInt) { + this.set("block_number", Value.fromBigInt(value)); + } + + get block_time(): BigInt | null { + let value = this.get("block_time"); + if (!value || value.kind == ValueKind.NULL) { + return null; + } else { + return value.toBigInt(); + } + } + + set block_time(value: BigInt | null) { + if (!value) { + this.unset("block_time"); + } else { + this.set("block_time", Value.fromBigInt(value)); + } + } + + get total_principal_tokens_committed(): BigInt { + let value = this.get("total_principal_tokens_committed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_committed(value: BigInt) { + this.set("total_principal_tokens_committed", Value.fromBigInt(value)); + } + + get total_principal_tokens_withdrawn(): BigInt { + let value = this.get("total_principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_withdrawn(value: BigInt) { + this.set("total_principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_collateral_tokens_deposited(): BigInt { + let value = this.get("total_collateral_tokens_deposited"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_deposited(value: BigInt) { + this.set("total_collateral_tokens_deposited", Value.fromBigInt(value)); + } + + get total_collateral_tokens_withdrawn(): BigInt { + let value = this.get("total_collateral_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_withdrawn(value: BigInt) { + this.set("total_collateral_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_borrowed(): BigInt { + let value = this.get("total_principal_tokens_borrowed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_borrowed(value: BigInt) { + this.set("total_principal_tokens_borrowed", Value.fromBigInt(value)); + } + + get total_principal_tokens_repaid(): BigInt { + let value = this.get("total_principal_tokens_repaid"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_repaid(value: BigInt) { + this.set("total_principal_tokens_repaid", Value.fromBigInt(value)); + } + + get total_interest_collected(): BigInt { + let value = this.get("total_interest_collected"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_interest_collected(value: BigInt) { + this.set("total_interest_collected", Value.fromBigInt(value)); + } + + get token_difference_from_liquidations(): BigInt { + let value = this.get("token_difference_from_liquidations"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set token_difference_from_liquidations(value: BigInt) { + this.set("token_difference_from_liquidations", Value.fromBigInt(value)); + } +} + +export class group_pool_metric_data_point_daily extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_pool_metric_data_point_daily entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_metric_data_point_daily must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_metric_data_point_daily", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_metric_data_point_daily | null { + return changetype( + store.get_in_block("group_pool_metric_data_point_daily", id) + ); + } + + static load(id: string): group_pool_metric_data_point_daily | null { + return changetype( + store.get("group_pool_metric_data_point_daily", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get block_number(): BigInt { + let value = this.get("block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set block_number(value: BigInt) { + this.set("block_number", Value.fromBigInt(value)); + } + + get block_time(): BigInt | null { + let value = this.get("block_time"); + if (!value || value.kind == ValueKind.NULL) { + return null; + } else { + return value.toBigInt(); + } + } + + set block_time(value: BigInt | null) { + if (!value) { + this.unset("block_time"); + } else { + this.set("block_time", Value.fromBigInt(value)); + } + } + + get total_principal_tokens_committed(): BigInt { + let value = this.get("total_principal_tokens_committed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_committed(value: BigInt) { + this.set("total_principal_tokens_committed", Value.fromBigInt(value)); + } + + get total_principal_tokens_withdrawn(): BigInt { + let value = this.get("total_principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_withdrawn(value: BigInt) { + this.set("total_principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_collateral_tokens_deposited(): BigInt { + let value = this.get("total_collateral_tokens_deposited"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_deposited(value: BigInt) { + this.set("total_collateral_tokens_deposited", Value.fromBigInt(value)); + } + + get total_collateral_tokens_withdrawn(): BigInt { + let value = this.get("total_collateral_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_withdrawn(value: BigInt) { + this.set("total_collateral_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_borrowed(): BigInt { + let value = this.get("total_principal_tokens_borrowed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_borrowed(value: BigInt) { + this.set("total_principal_tokens_borrowed", Value.fromBigInt(value)); + } + + get total_principal_tokens_repaid(): BigInt { + let value = this.get("total_principal_tokens_repaid"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_repaid(value: BigInt) { + this.set("total_principal_tokens_repaid", Value.fromBigInt(value)); + } + + get total_interest_collected(): BigInt { + let value = this.get("total_interest_collected"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_interest_collected(value: BigInt) { + this.set("total_interest_collected", Value.fromBigInt(value)); + } + + get token_difference_from_liquidations(): BigInt { + let value = this.get("token_difference_from_liquidations"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set token_difference_from_liquidations(value: BigInt) { + this.set("token_difference_from_liquidations", Value.fromBigInt(value)); + } +} + +export class group_pool_metric_data_point_weekly extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert( + id != null, + "Cannot save group_pool_metric_data_point_weekly entity without an ID" + ); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_pool_metric_data_point_weekly must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_pool_metric_data_point_weekly", id.toString(), this); + } + } + + static loadInBlock(id: string): group_pool_metric_data_point_weekly | null { + return changetype( + store.get_in_block("group_pool_metric_data_point_weekly", id) + ); + } + + static load(id: string): group_pool_metric_data_point_weekly | null { + return changetype( + store.get("group_pool_metric_data_point_weekly", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get block_number(): BigInt { + let value = this.get("block_number"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set block_number(value: BigInt) { + this.set("block_number", Value.fromBigInt(value)); + } + + get block_time(): BigInt | null { + let value = this.get("block_time"); + if (!value || value.kind == ValueKind.NULL) { + return null; + } else { + return value.toBigInt(); + } + } + + set block_time(value: BigInt | null) { + if (!value) { + this.unset("block_time"); + } else { + this.set("block_time", Value.fromBigInt(value)); + } + } + + get total_principal_tokens_committed(): BigInt { + let value = this.get("total_principal_tokens_committed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_committed(value: BigInt) { + this.set("total_principal_tokens_committed", Value.fromBigInt(value)); + } + + get total_principal_tokens_withdrawn(): BigInt { + let value = this.get("total_principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_withdrawn(value: BigInt) { + this.set("total_principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_collateral_tokens_deposited(): BigInt { + let value = this.get("total_collateral_tokens_deposited"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_deposited(value: BigInt) { + this.set("total_collateral_tokens_deposited", Value.fromBigInt(value)); + } + + get total_collateral_tokens_withdrawn(): BigInt { + let value = this.get("total_collateral_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_withdrawn(value: BigInt) { + this.set("total_collateral_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_borrowed(): BigInt { + let value = this.get("total_principal_tokens_borrowed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_borrowed(value: BigInt) { + this.set("total_principal_tokens_borrowed", Value.fromBigInt(value)); + } + + get total_principal_tokens_repaid(): BigInt { + let value = this.get("total_principal_tokens_repaid"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_repaid(value: BigInt) { + this.set("total_principal_tokens_repaid", Value.fromBigInt(value)); + } + + get total_interest_collected(): BigInt { + let value = this.get("total_interest_collected"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_interest_collected(value: BigInt) { + this.set("total_interest_collected", Value.fromBigInt(value)); + } + + get token_difference_from_liquidations(): BigInt { + let value = this.get("token_difference_from_liquidations"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set token_difference_from_liquidations(value: BigInt) { + this.set("token_difference_from_liquidations", Value.fromBigInt(value)); + } +} + +export class group_user_metric extends Entity { + constructor(id: string) { + super(); + this.set("id", Value.fromString(id)); + } + + save(): void { + let id = this.get("id"); + assert(id != null, "Cannot save group_user_metric entity without an ID"); + if (id) { + assert( + id.kind == ValueKind.STRING, + `Entities of type group_user_metric must have an ID of type String but the id '${id.displayData()}' is of type ${id.displayKind()}` + ); + store.set("group_user_metric", id.toString(), this); + } + } + + static loadInBlock(id: string): group_user_metric | null { + return changetype( + store.get_in_block("group_user_metric", id) + ); + } + + static load(id: string): group_user_metric | null { + return changetype( + store.get("group_user_metric", id) + ); + } + + get id(): string { + let value = this.get("id"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toString(); + } + } + + set id(value: string) { + this.set("id", Value.fromString(value)); + } + + get user_address(): Bytes { + let value = this.get("user_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set user_address(value: Bytes) { + this.set("user_address", Value.fromBytes(value)); + } + + get group_pool_address(): Bytes { + let value = this.get("group_pool_address"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBytes(); + } + } + + set group_pool_address(value: Bytes) { + this.set("group_pool_address", Value.fromBytes(value)); + } + + get total_principal_tokens_committed(): BigInt { + let value = this.get("total_principal_tokens_committed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_committed(value: BigInt) { + this.set("total_principal_tokens_committed", Value.fromBigInt(value)); + } + + get total_principal_tokens_withdrawn(): BigInt { + let value = this.get("total_principal_tokens_withdrawn"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_withdrawn(value: BigInt) { + this.set("total_principal_tokens_withdrawn", Value.fromBigInt(value)); + } + + get total_principal_tokens_borrowed(): BigInt { + let value = this.get("total_principal_tokens_borrowed"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_principal_tokens_borrowed(value: BigInt) { + this.set("total_principal_tokens_borrowed", Value.fromBigInt(value)); + } + + get total_collateral_tokens_deposited(): BigInt { + let value = this.get("total_collateral_tokens_deposited"); + if (!value || value.kind == ValueKind.NULL) { + throw new Error("Cannot return null for a required field."); + } else { + return value.toBigInt(); + } + } + + set total_collateral_tokens_deposited(value: BigInt) { + this.set("total_collateral_tokens_deposited", Value.fromBigInt(value)); + } +} diff --git a/packages/subgraph-pool-v3/generated/templates.ts b/packages/subgraph-pool-v3/generated/templates.ts new file mode 100644 index 000000000..f4a6dff6d --- /dev/null +++ b/packages/subgraph-pool-v3/generated/templates.ts @@ -0,0 +1,17 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + Address, + DataSourceTemplate, + DataSourceContext +} from "@graphprotocol/graph-ts"; + +export class Pool extends DataSourceTemplate { + static create(address: Address): void { + DataSourceTemplate.create("Pool", [address.toHex()]); + } + + static createWithContext(address: Address, context: DataSourceContext): void { + DataSourceTemplate.createWithContext("Pool", [address.toHex()], context); + } +} diff --git a/packages/subgraph-pool-v3/generated/templates/Pool/Factory.ts b/packages/subgraph-pool-v3/generated/templates/Pool/Factory.ts new file mode 100644 index 000000000..f04fc8e23 --- /dev/null +++ b/packages/subgraph-pool-v3/generated/templates/Pool/Factory.ts @@ -0,0 +1,383 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + ethereum, + JSONValue, + TypedMap, + Entity, + Bytes, + Address, + BigInt +} from "@graphprotocol/graph-ts"; + +export class DeployedLenderGroupContract extends ethereum.Event { + get params(): DeployedLenderGroupContract__Params { + return new DeployedLenderGroupContract__Params(this); + } +} + +export class DeployedLenderGroupContract__Params { + _event: DeployedLenderGroupContract; + + constructor(event: DeployedLenderGroupContract) { + this._event = event; + } + + get groupContract(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class Initialized extends ethereum.Event { + get params(): Initialized__Params { + return new Initialized__Params(this); + } +} + +export class Initialized__Params { + _event: Initialized; + + constructor(event: Initialized) { + this._event = event; + } + + get version(): i32 { + return this._event.parameters[0].value.toI32(); + } +} + +export class OwnershipTransferred extends ethereum.Event { + get params(): OwnershipTransferred__Params { + return new OwnershipTransferred__Params(this); + } +} + +export class OwnershipTransferred__Params { + _event: OwnershipTransferred; + + constructor(event: OwnershipTransferred) { + this._event = event; + } + + get previousOwner(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get newOwner(): Address { + return this._event.parameters[1].value.toAddress(); + } +} + +export class Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct extends ethereum.Tuple { + get principalTokenAddress(): Address { + return this[0].toAddress(); + } + + get collateralTokenAddress(): Address { + return this[1].toAddress(); + } + + get marketId(): BigInt { + return this[2].toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this[3].toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this[4].toI32(); + } + + get interestRateUpperBound(): i32 { + return this[5].toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this[6].toI32(); + } + + get collateralRatio(): i32 { + return this[7].toI32(); + } +} + +export class Factory extends ethereum.SmartContract { + static bind(address: Address): Factory { + return new Factory("Factory", address); + } + + deployLenderCommitmentGroupPool( + _initialPrincipalAmount: BigInt, + _commitmentGroupConfig: Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct, + _priceAdapterAddress: Address, + _priceAdapterRoute: Bytes + ): Address { + let result = super.call( + "deployLenderCommitmentGroupPool", + "deployLenderCommitmentGroupPool(uint256,(address,address,uint256,uint32,uint16,uint16,uint16,uint16),address,bytes):(address)", + [ + ethereum.Value.fromUnsignedBigInt(_initialPrincipalAmount), + ethereum.Value.fromTuple(_commitmentGroupConfig), + ethereum.Value.fromAddress(_priceAdapterAddress), + ethereum.Value.fromBytes(_priceAdapterRoute) + ] + ); + + return result[0].toAddress(); + } + + try_deployLenderCommitmentGroupPool( + _initialPrincipalAmount: BigInt, + _commitmentGroupConfig: Factory__deployLenderCommitmentGroupPoolInput_commitmentGroupConfigStruct, + _priceAdapterAddress: Address, + _priceAdapterRoute: Bytes + ): ethereum.CallResult
{ + let result = super.tryCall( + "deployLenderCommitmentGroupPool", + "deployLenderCommitmentGroupPool(uint256,(address,address,uint256,uint32,uint16,uint16,uint16,uint16),address,bytes):(address)", + [ + ethereum.Value.fromUnsignedBigInt(_initialPrincipalAmount), + ethereum.Value.fromTuple(_commitmentGroupConfig), + ethereum.Value.fromAddress(_priceAdapterAddress), + ethereum.Value.fromBytes(_priceAdapterRoute) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + deployedLenderGroupContracts(param0: Address): BigInt { + let result = super.call( + "deployedLenderGroupContracts", + "deployedLenderGroupContracts(address):(uint256)", + [ethereum.Value.fromAddress(param0)] + ); + + return result[0].toBigInt(); + } + + try_deployedLenderGroupContracts( + param0: Address + ): ethereum.CallResult { + let result = super.tryCall( + "deployedLenderGroupContracts", + "deployedLenderGroupContracts(address):(uint256)", + [ethereum.Value.fromAddress(param0)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + lenderGroupBeacon(): Address { + let result = super.call( + "lenderGroupBeacon", + "lenderGroupBeacon():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_lenderGroupBeacon(): ethereum.CallResult
{ + let result = super.tryCall( + "lenderGroupBeacon", + "lenderGroupBeacon():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + owner(): Address { + let result = super.call("owner", "owner():(address)", []); + + return result[0].toAddress(); + } + + try_owner(): ethereum.CallResult
{ + let result = super.tryCall("owner", "owner():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } +} + +export class DeployLenderCommitmentGroupPoolCall extends ethereum.Call { + get inputs(): DeployLenderCommitmentGroupPoolCall__Inputs { + return new DeployLenderCommitmentGroupPoolCall__Inputs(this); + } + + get outputs(): DeployLenderCommitmentGroupPoolCall__Outputs { + return new DeployLenderCommitmentGroupPoolCall__Outputs(this); + } +} + +export class DeployLenderCommitmentGroupPoolCall__Inputs { + _call: DeployLenderCommitmentGroupPoolCall; + + constructor(call: DeployLenderCommitmentGroupPoolCall) { + this._call = call; + } + + get _initialPrincipalAmount(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _commitmentGroupConfig(): DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct { + return changetype< + DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct + >(this._call.inputValues[1].value.toTuple()); + } + + get _priceAdapterAddress(): Address { + return this._call.inputValues[2].value.toAddress(); + } + + get _priceAdapterRoute(): Bytes { + return this._call.inputValues[3].value.toBytes(); + } +} + +export class DeployLenderCommitmentGroupPoolCall__Outputs { + _call: DeployLenderCommitmentGroupPoolCall; + + constructor(call: DeployLenderCommitmentGroupPoolCall) { + this._call = call; + } + + get value0(): Address { + return this._call.outputValues[0].value.toAddress(); + } +} + +export class DeployLenderCommitmentGroupPoolCall_commitmentGroupConfigStruct extends ethereum.Tuple { + get principalTokenAddress(): Address { + return this[0].toAddress(); + } + + get collateralTokenAddress(): Address { + return this[1].toAddress(); + } + + get marketId(): BigInt { + return this[2].toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this[3].toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this[4].toI32(); + } + + get interestRateUpperBound(): i32 { + return this[5].toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this[6].toI32(); + } + + get collateralRatio(): i32 { + return this[7].toI32(); + } +} + +export class InitializeCall extends ethereum.Call { + get inputs(): InitializeCall__Inputs { + return new InitializeCall__Inputs(this); + } + + get outputs(): InitializeCall__Outputs { + return new InitializeCall__Outputs(this); + } +} + +export class InitializeCall__Inputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } + + get _lenderGroupBeacon(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class InitializeCall__Outputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall extends ethereum.Call { + get inputs(): RenounceOwnershipCall__Inputs { + return new RenounceOwnershipCall__Inputs(this); + } + + get outputs(): RenounceOwnershipCall__Outputs { + return new RenounceOwnershipCall__Outputs(this); + } +} + +export class RenounceOwnershipCall__Inputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall__Outputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class TransferOwnershipCall extends ethereum.Call { + get inputs(): TransferOwnershipCall__Inputs { + return new TransferOwnershipCall__Inputs(this); + } + + get outputs(): TransferOwnershipCall__Outputs { + return new TransferOwnershipCall__Outputs(this); + } +} + +export class TransferOwnershipCall__Inputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } + + get newOwner(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class TransferOwnershipCall__Outputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } +} diff --git a/packages/subgraph-pool-v3/generated/templates/Pool/Pool.ts b/packages/subgraph-pool-v3/generated/templates/Pool/Pool.ts new file mode 100644 index 000000000..e58efce76 --- /dev/null +++ b/packages/subgraph-pool-v3/generated/templates/Pool/Pool.ts @@ -0,0 +1,3031 @@ +// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + +import { + ethereum, + JSONValue, + TypedMap, + Entity, + Bytes, + Address, + BigInt +} from "@graphprotocol/graph-ts"; + +export class Approval extends ethereum.Event { + get params(): Approval__Params { + return new Approval__Params(this); + } +} + +export class Approval__Params { + _event: Approval; + + constructor(event: Approval) { + this._event = event; + } + + get owner(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get spender(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get value(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } +} + +export class BorrowerAcceptedFunds extends ethereum.Event { + get params(): BorrowerAcceptedFunds__Params { + return new BorrowerAcceptedFunds__Params(this); + } +} + +export class BorrowerAcceptedFunds__Params { + _event: BorrowerAcceptedFunds; + + constructor(event: BorrowerAcceptedFunds) { + this._event = event; + } + + get borrower(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get bidId(): BigInt { + return this._event.parameters[1].value.toBigInt(); + } + + get principalAmount(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } + + get collateralAmount(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get loanDuration(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } + + get interestRate(): i32 { + return this._event.parameters[5].value.toI32(); + } +} + +export class DefaultedLoanLiquidated extends ethereum.Event { + get params(): DefaultedLoanLiquidated__Params { + return new DefaultedLoanLiquidated__Params(this); + } +} + +export class DefaultedLoanLiquidated__Params { + _event: DefaultedLoanLiquidated; + + constructor(event: DefaultedLoanLiquidated) { + this._event = event; + } + + get bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get liquidator(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get amountDue(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } + + get tokenAmountDifference(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } +} + +export class Deposit extends ethereum.Event { + get params(): Deposit__Params { + return new Deposit__Params(this); + } +} + +export class Deposit__Params { + _event: Deposit; + + constructor(event: Deposit) { + this._event = event; + } + + get caller(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get owner(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get assets(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } + + get shares(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } +} + +export class Initialized extends ethereum.Event { + get params(): Initialized__Params { + return new Initialized__Params(this); + } +} + +export class Initialized__Params { + _event: Initialized; + + constructor(event: Initialized) { + this._event = event; + } + + get version(): i32 { + return this._event.parameters[0].value.toI32(); + } +} + +export class LoanRepaid extends ethereum.Event { + get params(): LoanRepaid__Params { + return new LoanRepaid__Params(this); + } +} + +export class LoanRepaid__Params { + _event: LoanRepaid; + + constructor(event: LoanRepaid) { + this._event = event; + } + + get bidId(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } + + get repayer(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get principalAmount(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } + + get interestAmount(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get totalPrincipalRepaid(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } + + get totalInterestCollected(): BigInt { + return this._event.parameters[5].value.toBigInt(); + } +} + +export class OwnershipTransferred extends ethereum.Event { + get params(): OwnershipTransferred__Params { + return new OwnershipTransferred__Params(this); + } +} + +export class OwnershipTransferred__Params { + _event: OwnershipTransferred; + + constructor(event: OwnershipTransferred) { + this._event = event; + } + + get previousOwner(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get newOwner(): Address { + return this._event.parameters[1].value.toAddress(); + } +} + +export class Paused extends ethereum.Event { + get params(): Paused__Params { + return new Paused__Params(this); + } +} + +export class Paused__Params { + _event: Paused; + + constructor(event: Paused) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class PausedBorrowing extends ethereum.Event { + get params(): PausedBorrowing__Params { + return new PausedBorrowing__Params(this); + } +} + +export class PausedBorrowing__Params { + _event: PausedBorrowing; + + constructor(event: PausedBorrowing) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class PausedLiquidationAuction extends ethereum.Event { + get params(): PausedLiquidationAuction__Params { + return new PausedLiquidationAuction__Params(this); + } +} + +export class PausedLiquidationAuction__Params { + _event: PausedLiquidationAuction; + + constructor(event: PausedLiquidationAuction) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class PoolInitialized extends ethereum.Event { + get params(): PoolInitialized__Params { + return new PoolInitialized__Params(this); + } +} + +export class PoolInitialized__Params { + _event: PoolInitialized; + + constructor(event: PoolInitialized) { + this._event = event; + } + + get principalTokenAddress(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get collateralTokenAddress(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get marketId(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this._event.parameters[4].value.toI32(); + } + + get interestRateUpperBound(): i32 { + return this._event.parameters[5].value.toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this._event.parameters[6].value.toI32(); + } + + get loanToValuePercent(): i32 { + return this._event.parameters[7].value.toI32(); + } +} + +export class SharesLastTransferredAt extends ethereum.Event { + get params(): SharesLastTransferredAt__Params { + return new SharesLastTransferredAt__Params(this); + } +} + +export class SharesLastTransferredAt__Params { + _event: SharesLastTransferredAt; + + constructor(event: SharesLastTransferredAt) { + this._event = event; + } + + get recipient(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get transferredAt(): BigInt { + return this._event.parameters[1].value.toBigInt(); + } +} + +export class Transfer extends ethereum.Event { + get params(): Transfer__Params { + return new Transfer__Params(this); + } +} + +export class Transfer__Params { + _event: Transfer; + + constructor(event: Transfer) { + this._event = event; + } + + get from(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get to(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get value(): BigInt { + return this._event.parameters[2].value.toBigInt(); + } +} + +export class Unpaused extends ethereum.Event { + get params(): Unpaused__Params { + return new Unpaused__Params(this); + } +} + +export class Unpaused__Params { + _event: Unpaused; + + constructor(event: Unpaused) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class UnpausedBorrowing extends ethereum.Event { + get params(): UnpausedBorrowing__Params { + return new UnpausedBorrowing__Params(this); + } +} + +export class UnpausedBorrowing__Params { + _event: UnpausedBorrowing; + + constructor(event: UnpausedBorrowing) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class UnpausedLiquidationAuction extends ethereum.Event { + get params(): UnpausedLiquidationAuction__Params { + return new UnpausedLiquidationAuction__Params(this); + } +} + +export class UnpausedLiquidationAuction__Params { + _event: UnpausedLiquidationAuction; + + constructor(event: UnpausedLiquidationAuction) { + this._event = event; + } + + get account(): Address { + return this._event.parameters[0].value.toAddress(); + } +} + +export class Withdraw extends ethereum.Event { + get params(): Withdraw__Params { + return new Withdraw__Params(this); + } +} + +export class Withdraw__Params { + _event: Withdraw; + + constructor(event: Withdraw) { + this._event = event; + } + + get caller(): Address { + return this._event.parameters[0].value.toAddress(); + } + + get receiver(): Address { + return this._event.parameters[1].value.toAddress(); + } + + get owner(): Address { + return this._event.parameters[2].value.toAddress(); + } + + get assets(): BigInt { + return this._event.parameters[3].value.toBigInt(); + } + + get shares(): BigInt { + return this._event.parameters[4].value.toBigInt(); + } +} + +export class WithdrawFromEscrow extends ethereum.Event { + get params(): WithdrawFromEscrow__Params { + return new WithdrawFromEscrow__Params(this); + } +} + +export class WithdrawFromEscrow__Params { + _event: WithdrawFromEscrow; + + constructor(event: WithdrawFromEscrow) { + this._event = event; + } + + get amount(): BigInt { + return this._event.parameters[0].value.toBigInt(); + } +} + +export class Pool extends ethereum.SmartContract { + static bind(address: Address): Pool { + return new Pool("Pool", address); + } + + DEFAULT_WITHDRAW_DELAY_TIME_SECONDS(): BigInt { + let result = super.call( + "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_DEFAULT_WITHDRAW_DELAY_TIME_SECONDS(): ethereum.CallResult { + let result = super.tryCall( + "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS", + "DEFAULT_WITHDRAW_DELAY_TIME_SECONDS():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + EXCHANGE_RATE_EXPANSION_FACTOR(): BigInt { + let result = super.call( + "EXCHANGE_RATE_EXPANSION_FACTOR", + "EXCHANGE_RATE_EXPANSION_FACTOR():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_EXCHANGE_RATE_EXPANSION_FACTOR(): ethereum.CallResult { + let result = super.tryCall( + "EXCHANGE_RATE_EXPANSION_FACTOR", + "EXCHANGE_RATE_EXPANSION_FACTOR():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + MAX_WITHDRAW_DELAY_TIME(): BigInt { + let result = super.call( + "MAX_WITHDRAW_DELAY_TIME", + "MAX_WITHDRAW_DELAY_TIME():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_MAX_WITHDRAW_DELAY_TIME(): ethereum.CallResult { + let result = super.tryCall( + "MAX_WITHDRAW_DELAY_TIME", + "MAX_WITHDRAW_DELAY_TIME():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + MIN_TWAP_INTERVAL(): BigInt { + let result = super.call( + "MIN_TWAP_INTERVAL", + "MIN_TWAP_INTERVAL():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_MIN_TWAP_INTERVAL(): ethereum.CallResult { + let result = super.tryCall( + "MIN_TWAP_INTERVAL", + "MIN_TWAP_INTERVAL():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + ORACLE_MANAGER(): Address { + let result = super.call("ORACLE_MANAGER", "ORACLE_MANAGER():(address)", []); + + return result[0].toAddress(); + } + + try_ORACLE_MANAGER(): ethereum.CallResult
{ + let result = super.tryCall( + "ORACLE_MANAGER", + "ORACLE_MANAGER():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + SMART_COMMITMENT_FORWARDER(): Address { + let result = super.call( + "SMART_COMMITMENT_FORWARDER", + "SMART_COMMITMENT_FORWARDER():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_SMART_COMMITMENT_FORWARDER(): ethereum.CallResult
{ + let result = super.tryCall( + "SMART_COMMITMENT_FORWARDER", + "SMART_COMMITMENT_FORWARDER():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + TELLER_V2(): Address { + let result = super.call("TELLER_V2", "TELLER_V2():(address)", []); + + return result[0].toAddress(); + } + + try_TELLER_V2(): ethereum.CallResult
{ + let result = super.tryCall("TELLER_V2", "TELLER_V2():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + UNISWAP_EXPANSION_FACTOR(): BigInt { + let result = super.call( + "UNISWAP_EXPANSION_FACTOR", + "UNISWAP_EXPANSION_FACTOR():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_UNISWAP_EXPANSION_FACTOR(): ethereum.CallResult { + let result = super.tryCall( + "UNISWAP_EXPANSION_FACTOR", + "UNISWAP_EXPANSION_FACTOR():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + activeBids(param0: BigInt): boolean { + let result = super.call("activeBids", "activeBids(uint256):(bool)", [ + ethereum.Value.fromUnsignedBigInt(param0) + ]); + + return result[0].toBoolean(); + } + + try_activeBids(param0: BigInt): ethereum.CallResult { + let result = super.tryCall("activeBids", "activeBids(uint256):(bool)", [ + ethereum.Value.fromUnsignedBigInt(param0) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + activeBidsAmountDueRemaining(param0: BigInt): BigInt { + let result = super.call( + "activeBidsAmountDueRemaining", + "activeBidsAmountDueRemaining(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(param0)] + ); + + return result[0].toBigInt(); + } + + try_activeBidsAmountDueRemaining( + param0: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "activeBidsAmountDueRemaining", + "activeBidsAmountDueRemaining(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(param0)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + allowance(owner: Address, spender: Address): BigInt { + let result = super.call( + "allowance", + "allowance(address,address):(uint256)", + [ethereum.Value.fromAddress(owner), ethereum.Value.fromAddress(spender)] + ); + + return result[0].toBigInt(); + } + + try_allowance(owner: Address, spender: Address): ethereum.CallResult { + let result = super.tryCall( + "allowance", + "allowance(address,address):(uint256)", + [ethereum.Value.fromAddress(owner), ethereum.Value.fromAddress(spender)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + approve(spender: Address, amount: BigInt): boolean { + let result = super.call("approve", "approve(address,uint256):(bool)", [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(amount) + ]); + + return result[0].toBoolean(); + } + + try_approve(spender: Address, amount: BigInt): ethereum.CallResult { + let result = super.tryCall("approve", "approve(address,uint256):(bool)", [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(amount) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + asset(): Address { + let result = super.call("asset", "asset():(address)", []); + + return result[0].toAddress(); + } + + try_asset(): ethereum.CallResult
{ + let result = super.tryCall("asset", "asset():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + balanceOf(account: Address): BigInt { + let result = super.call("balanceOf", "balanceOf(address):(uint256)", [ + ethereum.Value.fromAddress(account) + ]); + + return result[0].toBigInt(); + } + + try_balanceOf(account: Address): ethereum.CallResult { + let result = super.tryCall("balanceOf", "balanceOf(address):(uint256)", [ + ethereum.Value.fromAddress(account) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + borrowingPaused(): boolean { + let result = super.call("borrowingPaused", "borrowingPaused():(bool)", []); + + return result[0].toBoolean(); + } + + try_borrowingPaused(): ethereum.CallResult { + let result = super.tryCall( + "borrowingPaused", + "borrowingPaused():(bool)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + calculateCollateralRequiredToBorrowPrincipal( + _principalAmount: BigInt + ): BigInt { + let result = super.call( + "calculateCollateralRequiredToBorrowPrincipal", + "calculateCollateralRequiredToBorrowPrincipal(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(_principalAmount)] + ); + + return result[0].toBigInt(); + } + + try_calculateCollateralRequiredToBorrowPrincipal( + _principalAmount: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "calculateCollateralRequiredToBorrowPrincipal", + "calculateCollateralRequiredToBorrowPrincipal(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(_principalAmount)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + calculateCollateralTokensAmountEquivalentToPrincipalTokens( + principalAmount: BigInt + ): BigInt { + let result = super.call( + "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "calculateCollateralTokensAmountEquivalentToPrincipalTokens(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(principalAmount)] + ); + + return result[0].toBigInt(); + } + + try_calculateCollateralTokensAmountEquivalentToPrincipalTokens( + principalAmount: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "calculateCollateralTokensAmountEquivalentToPrincipalTokens", + "calculateCollateralTokensAmountEquivalentToPrincipalTokens(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(principalAmount)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + collateralRatio(): i32 { + let result = super.call( + "collateralRatio", + "collateralRatio():(uint16)", + [] + ); + + return result[0].toI32(); + } + + try_collateralRatio(): ethereum.CallResult { + let result = super.tryCall( + "collateralRatio", + "collateralRatio():(uint16)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + collateralToken(): Address { + let result = super.call( + "collateralToken", + "collateralToken():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_collateralToken(): ethereum.CallResult
{ + let result = super.tryCall( + "collateralToken", + "collateralToken():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + convertToAssets(shares: BigInt): BigInt { + let result = super.call( + "convertToAssets", + "convertToAssets(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(shares)] + ); + + return result[0].toBigInt(); + } + + try_convertToAssets(shares: BigInt): ethereum.CallResult { + let result = super.tryCall( + "convertToAssets", + "convertToAssets(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(shares)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + convertToShares(assets: BigInt): BigInt { + let result = super.call( + "convertToShares", + "convertToShares(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + + return result[0].toBigInt(); + } + + try_convertToShares(assets: BigInt): ethereum.CallResult { + let result = super.tryCall( + "convertToShares", + "convertToShares(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + decimals(): i32 { + let result = super.call("decimals", "decimals():(uint8)", []); + + return result[0].toI32(); + } + + try_decimals(): ethereum.CallResult { + let result = super.tryCall("decimals", "decimals():(uint8)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + decreaseAllowance(spender: Address, subtractedValue: BigInt): boolean { + let result = super.call( + "decreaseAllowance", + "decreaseAllowance(address,uint256):(bool)", + [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(subtractedValue) + ] + ); + + return result[0].toBoolean(); + } + + try_decreaseAllowance( + spender: Address, + subtractedValue: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "decreaseAllowance", + "decreaseAllowance(address,uint256):(bool)", + [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(subtractedValue) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + deposit(assets: BigInt, receiver: Address): BigInt { + let result = super.call("deposit", "deposit(uint256,address):(uint256)", [ + ethereum.Value.fromUnsignedBigInt(assets), + ethereum.Value.fromAddress(receiver) + ]); + + return result[0].toBigInt(); + } + + try_deposit(assets: BigInt, receiver: Address): ethereum.CallResult { + let result = super.tryCall( + "deposit", + "deposit(uint256,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(assets), + ethereum.Value.fromAddress(receiver) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + excessivePrincipalTokensRepaid(): BigInt { + let result = super.call( + "excessivePrincipalTokensRepaid", + "excessivePrincipalTokensRepaid():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_excessivePrincipalTokensRepaid(): ethereum.CallResult { + let result = super.tryCall( + "excessivePrincipalTokensRepaid", + "excessivePrincipalTokensRepaid():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + firstDepositMade(): boolean { + let result = super.call( + "firstDepositMade", + "firstDepositMade():(bool)", + [] + ); + + return result[0].toBoolean(); + } + + try_firstDepositMade(): ethereum.CallResult { + let result = super.tryCall( + "firstDepositMade", + "firstDepositMade():(bool)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + getCollateralTokenAddress(): Address { + let result = super.call( + "getCollateralTokenAddress", + "getCollateralTokenAddress():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_getCollateralTokenAddress(): ethereum.CallResult
{ + let result = super.tryCall( + "getCollateralTokenAddress", + "getCollateralTokenAddress():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + getCollateralTokenType(): i32 { + let result = super.call( + "getCollateralTokenType", + "getCollateralTokenType():(uint8)", + [] + ); + + return result[0].toI32(); + } + + try_getCollateralTokenType(): ethereum.CallResult { + let result = super.tryCall( + "getCollateralTokenType", + "getCollateralTokenType():(uint8)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + getLastUnpausedAt(): BigInt { + let result = super.call( + "getLastUnpausedAt", + "getLastUnpausedAt():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_getLastUnpausedAt(): ethereum.CallResult { + let result = super.tryCall( + "getLastUnpausedAt", + "getLastUnpausedAt():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getMarketId(): BigInt { + let result = super.call("getMarketId", "getMarketId():(uint256)", []); + + return result[0].toBigInt(); + } + + try_getMarketId(): ethereum.CallResult { + let result = super.tryCall("getMarketId", "getMarketId():(uint256)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getMaxLoanDuration(): BigInt { + let result = super.call( + "getMaxLoanDuration", + "getMaxLoanDuration():(uint32)", + [] + ); + + return result[0].toBigInt(); + } + + try_getMaxLoanDuration(): ethereum.CallResult { + let result = super.tryCall( + "getMaxLoanDuration", + "getMaxLoanDuration():(uint32)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getMinInterestRate(amountDelta: BigInt): i32 { + let result = super.call( + "getMinInterestRate", + "getMinInterestRate(uint256):(uint16)", + [ethereum.Value.fromUnsignedBigInt(amountDelta)] + ); + + return result[0].toI32(); + } + + try_getMinInterestRate(amountDelta: BigInt): ethereum.CallResult { + let result = super.tryCall( + "getMinInterestRate", + "getMinInterestRate(uint256):(uint16)", + [ethereum.Value.fromUnsignedBigInt(amountDelta)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + getMinimumAmountDifferenceToCloseDefaultedLoan( + _amountOwed: BigInt, + _loanDefaultedTimestamp: BigInt + ): BigInt { + let result = super.call( + "getMinimumAmountDifferenceToCloseDefaultedLoan", + "getMinimumAmountDifferenceToCloseDefaultedLoan(uint256,uint256):(int256)", + [ + ethereum.Value.fromUnsignedBigInt(_amountOwed), + ethereum.Value.fromUnsignedBigInt(_loanDefaultedTimestamp) + ] + ); + + return result[0].toBigInt(); + } + + try_getMinimumAmountDifferenceToCloseDefaultedLoan( + _amountOwed: BigInt, + _loanDefaultedTimestamp: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "getMinimumAmountDifferenceToCloseDefaultedLoan", + "getMinimumAmountDifferenceToCloseDefaultedLoan(uint256,uint256):(int256)", + [ + ethereum.Value.fromUnsignedBigInt(_amountOwed), + ethereum.Value.fromUnsignedBigInt(_loanDefaultedTimestamp) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getPoolUtilizationRatio(activeLoansAmountDelta: BigInt): i32 { + let result = super.call( + "getPoolUtilizationRatio", + "getPoolUtilizationRatio(uint256):(uint16)", + [ethereum.Value.fromUnsignedBigInt(activeLoansAmountDelta)] + ); + + return result[0].toI32(); + } + + try_getPoolUtilizationRatio( + activeLoansAmountDelta: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "getPoolUtilizationRatio", + "getPoolUtilizationRatio(uint256):(uint16)", + [ethereum.Value.fromUnsignedBigInt(activeLoansAmountDelta)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + getPrincipalAmountAvailableToBorrow(): BigInt { + let result = super.call( + "getPrincipalAmountAvailableToBorrow", + "getPrincipalAmountAvailableToBorrow():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_getPrincipalAmountAvailableToBorrow(): ethereum.CallResult { + let result = super.tryCall( + "getPrincipalAmountAvailableToBorrow", + "getPrincipalAmountAvailableToBorrow():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getPrincipalTokenAddress(): Address { + let result = super.call( + "getPrincipalTokenAddress", + "getPrincipalTokenAddress():(address)", + [] + ); + + return result[0].toAddress(); + } + + try_getPrincipalTokenAddress(): ethereum.CallResult
{ + let result = super.tryCall( + "getPrincipalTokenAddress", + "getPrincipalTokenAddress():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + getSharesLastTransferredAt(owner: Address): BigInt { + let result = super.call( + "getSharesLastTransferredAt", + "getSharesLastTransferredAt(address):(uint256)", + [ethereum.Value.fromAddress(owner)] + ); + + return result[0].toBigInt(); + } + + try_getSharesLastTransferredAt(owner: Address): ethereum.CallResult { + let result = super.tryCall( + "getSharesLastTransferredAt", + "getSharesLastTransferredAt(address):(uint256)", + [ethereum.Value.fromAddress(owner)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + getTokenDifferenceFromLiquidations(): BigInt { + let result = super.call( + "getTokenDifferenceFromLiquidations", + "getTokenDifferenceFromLiquidations():(int256)", + [] + ); + + return result[0].toBigInt(); + } + + try_getTokenDifferenceFromLiquidations(): ethereum.CallResult { + let result = super.tryCall( + "getTokenDifferenceFromLiquidations", + "getTokenDifferenceFromLiquidations():(int256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + increaseAllowance(spender: Address, addedValue: BigInt): boolean { + let result = super.call( + "increaseAllowance", + "increaseAllowance(address,uint256):(bool)", + [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(addedValue) + ] + ); + + return result[0].toBoolean(); + } + + try_increaseAllowance( + spender: Address, + addedValue: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "increaseAllowance", + "increaseAllowance(address,uint256):(bool)", + [ + ethereum.Value.fromAddress(spender), + ethereum.Value.fromUnsignedBigInt(addedValue) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + interestRateLowerBound(): i32 { + let result = super.call( + "interestRateLowerBound", + "interestRateLowerBound():(uint16)", + [] + ); + + return result[0].toI32(); + } + + try_interestRateLowerBound(): ethereum.CallResult { + let result = super.tryCall( + "interestRateLowerBound", + "interestRateLowerBound():(uint16)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + interestRateUpperBound(): i32 { + let result = super.call( + "interestRateUpperBound", + "interestRateUpperBound():(uint16)", + [] + ); + + return result[0].toI32(); + } + + try_interestRateUpperBound(): ethereum.CallResult { + let result = super.tryCall( + "interestRateUpperBound", + "interestRateUpperBound():(uint16)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + lastUnpausedAt(): BigInt { + let result = super.call("lastUnpausedAt", "lastUnpausedAt():(uint256)", []); + + return result[0].toBigInt(); + } + + try_lastUnpausedAt(): ethereum.CallResult { + let result = super.tryCall( + "lastUnpausedAt", + "lastUnpausedAt():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + liquidationAuctionPaused(): boolean { + let result = super.call( + "liquidationAuctionPaused", + "liquidationAuctionPaused():(bool)", + [] + ); + + return result[0].toBoolean(); + } + + try_liquidationAuctionPaused(): ethereum.CallResult { + let result = super.tryCall( + "liquidationAuctionPaused", + "liquidationAuctionPaused():(bool)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + liquidityThresholdPercent(): i32 { + let result = super.call( + "liquidityThresholdPercent", + "liquidityThresholdPercent():(uint16)", + [] + ); + + return result[0].toI32(); + } + + try_liquidityThresholdPercent(): ethereum.CallResult { + let result = super.tryCall( + "liquidityThresholdPercent", + "liquidityThresholdPercent():(uint16)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toI32()); + } + + maxDeposit(param0: Address): BigInt { + let result = super.call("maxDeposit", "maxDeposit(address):(uint256)", [ + ethereum.Value.fromAddress(param0) + ]); + + return result[0].toBigInt(); + } + + try_maxDeposit(param0: Address): ethereum.CallResult { + let result = super.tryCall("maxDeposit", "maxDeposit(address):(uint256)", [ + ethereum.Value.fromAddress(param0) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + maxLoanDuration(): BigInt { + let result = super.call( + "maxLoanDuration", + "maxLoanDuration():(uint32)", + [] + ); + + return result[0].toBigInt(); + } + + try_maxLoanDuration(): ethereum.CallResult { + let result = super.tryCall( + "maxLoanDuration", + "maxLoanDuration():(uint32)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + maxMint(param0: Address): BigInt { + let result = super.call("maxMint", "maxMint(address):(uint256)", [ + ethereum.Value.fromAddress(param0) + ]); + + return result[0].toBigInt(); + } + + try_maxMint(param0: Address): ethereum.CallResult { + let result = super.tryCall("maxMint", "maxMint(address):(uint256)", [ + ethereum.Value.fromAddress(param0) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + maxPrincipalPerCollateralAmount(): BigInt { + let result = super.call( + "maxPrincipalPerCollateralAmount", + "maxPrincipalPerCollateralAmount():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_maxPrincipalPerCollateralAmount(): ethereum.CallResult { + let result = super.tryCall( + "maxPrincipalPerCollateralAmount", + "maxPrincipalPerCollateralAmount():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + maxRedeem(owner: Address): BigInt { + let result = super.call("maxRedeem", "maxRedeem(address):(uint256)", [ + ethereum.Value.fromAddress(owner) + ]); + + return result[0].toBigInt(); + } + + try_maxRedeem(owner: Address): ethereum.CallResult { + let result = super.tryCall("maxRedeem", "maxRedeem(address):(uint256)", [ + ethereum.Value.fromAddress(owner) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + maxWithdraw(owner: Address): BigInt { + let result = super.call("maxWithdraw", "maxWithdraw(address):(uint256)", [ + ethereum.Value.fromAddress(owner) + ]); + + return result[0].toBigInt(); + } + + try_maxWithdraw(owner: Address): ethereum.CallResult { + let result = super.tryCall( + "maxWithdraw", + "maxWithdraw(address):(uint256)", + [ethereum.Value.fromAddress(owner)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + mint(shares: BigInt, receiver: Address): BigInt { + let result = super.call("mint", "mint(uint256,address):(uint256)", [ + ethereum.Value.fromUnsignedBigInt(shares), + ethereum.Value.fromAddress(receiver) + ]); + + return result[0].toBigInt(); + } + + try_mint(shares: BigInt, receiver: Address): ethereum.CallResult { + let result = super.tryCall("mint", "mint(uint256,address):(uint256)", [ + ethereum.Value.fromUnsignedBigInt(shares), + ethereum.Value.fromAddress(receiver) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + name(): string { + let result = super.call("name", "name():(string)", []); + + return result[0].toString(); + } + + try_name(): ethereum.CallResult { + let result = super.tryCall("name", "name():(string)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toString()); + } + + owner(): Address { + let result = super.call("owner", "owner():(address)", []); + + return result[0].toAddress(); + } + + try_owner(): ethereum.CallResult
{ + let result = super.tryCall("owner", "owner():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + paused(): boolean { + let result = super.call("paused", "paused():(bool)", []); + + return result[0].toBoolean(); + } + + try_paused(): ethereum.CallResult { + let result = super.tryCall("paused", "paused():(bool)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + previewDeposit(assets: BigInt): BigInt { + let result = super.call( + "previewDeposit", + "previewDeposit(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + + return result[0].toBigInt(); + } + + try_previewDeposit(assets: BigInt): ethereum.CallResult { + let result = super.tryCall( + "previewDeposit", + "previewDeposit(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + previewMint(shares: BigInt): BigInt { + let result = super.call("previewMint", "previewMint(uint256):(uint256)", [ + ethereum.Value.fromUnsignedBigInt(shares) + ]); + + return result[0].toBigInt(); + } + + try_previewMint(shares: BigInt): ethereum.CallResult { + let result = super.tryCall( + "previewMint", + "previewMint(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(shares)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + previewRedeem(shares: BigInt): BigInt { + let result = super.call( + "previewRedeem", + "previewRedeem(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(shares)] + ); + + return result[0].toBigInt(); + } + + try_previewRedeem(shares: BigInt): ethereum.CallResult { + let result = super.tryCall( + "previewRedeem", + "previewRedeem(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(shares)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + previewWithdraw(assets: BigInt): BigInt { + let result = super.call( + "previewWithdraw", + "previewWithdraw(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + + return result[0].toBigInt(); + } + + try_previewWithdraw(assets: BigInt): ethereum.CallResult { + let result = super.tryCall( + "previewWithdraw", + "previewWithdraw(uint256):(uint256)", + [ethereum.Value.fromUnsignedBigInt(assets)] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + priceAdapter(): Address { + let result = super.call("priceAdapter", "priceAdapter():(address)", []); + + return result[0].toAddress(); + } + + try_priceAdapter(): ethereum.CallResult
{ + let result = super.tryCall("priceAdapter", "priceAdapter():(address)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + priceRouteHash(): Bytes { + let result = super.call("priceRouteHash", "priceRouteHash():(bytes32)", []); + + return result[0].toBytes(); + } + + try_priceRouteHash(): ethereum.CallResult { + let result = super.tryCall( + "priceRouteHash", + "priceRouteHash():(bytes32)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBytes()); + } + + principalToken(): Address { + let result = super.call("principalToken", "principalToken():(address)", []); + + return result[0].toAddress(); + } + + try_principalToken(): ethereum.CallResult
{ + let result = super.tryCall( + "principalToken", + "principalToken():(address)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toAddress()); + } + + redeem(shares: BigInt, receiver: Address, owner: Address): BigInt { + let result = super.call( + "redeem", + "redeem(uint256,address,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(shares), + ethereum.Value.fromAddress(receiver), + ethereum.Value.fromAddress(owner) + ] + ); + + return result[0].toBigInt(); + } + + try_redeem( + shares: BigInt, + receiver: Address, + owner: Address + ): ethereum.CallResult { + let result = super.tryCall( + "redeem", + "redeem(uint256,address,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(shares), + ethereum.Value.fromAddress(receiver), + ethereum.Value.fromAddress(owner) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + sharesExchangeRate(): BigInt { + let result = super.call( + "sharesExchangeRate", + "sharesExchangeRate():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_sharesExchangeRate(): ethereum.CallResult { + let result = super.tryCall( + "sharesExchangeRate", + "sharesExchangeRate():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + sharesExchangeRateInverse(): BigInt { + let result = super.call( + "sharesExchangeRateInverse", + "sharesExchangeRateInverse():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_sharesExchangeRateInverse(): ethereum.CallResult { + let result = super.tryCall( + "sharesExchangeRateInverse", + "sharesExchangeRateInverse():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + symbol(): string { + let result = super.call("symbol", "symbol():(string)", []); + + return result[0].toString(); + } + + try_symbol(): ethereum.CallResult { + let result = super.tryCall("symbol", "symbol():(string)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toString()); + } + + totalAssets(): BigInt { + let result = super.call("totalAssets", "totalAssets():(uint256)", []); + + return result[0].toBigInt(); + } + + try_totalAssets(): ethereum.CallResult { + let result = super.tryCall("totalAssets", "totalAssets():(uint256)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalInterestCollected(): BigInt { + let result = super.call( + "totalInterestCollected", + "totalInterestCollected():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_totalInterestCollected(): ethereum.CallResult { + let result = super.tryCall( + "totalInterestCollected", + "totalInterestCollected():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalPrincipalTokensCommitted(): BigInt { + let result = super.call( + "totalPrincipalTokensCommitted", + "totalPrincipalTokensCommitted():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_totalPrincipalTokensCommitted(): ethereum.CallResult { + let result = super.tryCall( + "totalPrincipalTokensCommitted", + "totalPrincipalTokensCommitted():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalPrincipalTokensLended(): BigInt { + let result = super.call( + "totalPrincipalTokensLended", + "totalPrincipalTokensLended():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_totalPrincipalTokensLended(): ethereum.CallResult { + let result = super.tryCall( + "totalPrincipalTokensLended", + "totalPrincipalTokensLended():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalPrincipalTokensRepaid(): BigInt { + let result = super.call( + "totalPrincipalTokensRepaid", + "totalPrincipalTokensRepaid():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_totalPrincipalTokensRepaid(): ethereum.CallResult { + let result = super.tryCall( + "totalPrincipalTokensRepaid", + "totalPrincipalTokensRepaid():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalPrincipalTokensWithdrawn(): BigInt { + let result = super.call( + "totalPrincipalTokensWithdrawn", + "totalPrincipalTokensWithdrawn():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_totalPrincipalTokensWithdrawn(): ethereum.CallResult { + let result = super.tryCall( + "totalPrincipalTokensWithdrawn", + "totalPrincipalTokensWithdrawn():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + totalSupply(): BigInt { + let result = super.call("totalSupply", "totalSupply():(uint256)", []); + + return result[0].toBigInt(); + } + + try_totalSupply(): ethereum.CallResult { + let result = super.tryCall("totalSupply", "totalSupply():(uint256)", []); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + transfer(to: Address, amount: BigInt): boolean { + let result = super.call("transfer", "transfer(address,uint256):(bool)", [ + ethereum.Value.fromAddress(to), + ethereum.Value.fromUnsignedBigInt(amount) + ]); + + return result[0].toBoolean(); + } + + try_transfer(to: Address, amount: BigInt): ethereum.CallResult { + let result = super.tryCall("transfer", "transfer(address,uint256):(bool)", [ + ethereum.Value.fromAddress(to), + ethereum.Value.fromUnsignedBigInt(amount) + ]); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + transferFrom(from: Address, to: Address, amount: BigInt): boolean { + let result = super.call( + "transferFrom", + "transferFrom(address,address,uint256):(bool)", + [ + ethereum.Value.fromAddress(from), + ethereum.Value.fromAddress(to), + ethereum.Value.fromUnsignedBigInt(amount) + ] + ); + + return result[0].toBoolean(); + } + + try_transferFrom( + from: Address, + to: Address, + amount: BigInt + ): ethereum.CallResult { + let result = super.tryCall( + "transferFrom", + "transferFrom(address,address,uint256):(bool)", + [ + ethereum.Value.fromAddress(from), + ethereum.Value.fromAddress(to), + ethereum.Value.fromUnsignedBigInt(amount) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBoolean()); + } + + withdraw(assets: BigInt, receiver: Address, owner: Address): BigInt { + let result = super.call( + "withdraw", + "withdraw(uint256,address,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(assets), + ethereum.Value.fromAddress(receiver), + ethereum.Value.fromAddress(owner) + ] + ); + + return result[0].toBigInt(); + } + + try_withdraw( + assets: BigInt, + receiver: Address, + owner: Address + ): ethereum.CallResult { + let result = super.tryCall( + "withdraw", + "withdraw(uint256,address,address):(uint256)", + [ + ethereum.Value.fromUnsignedBigInt(assets), + ethereum.Value.fromAddress(receiver), + ethereum.Value.fromAddress(owner) + ] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } + + withdrawDelayTimeSeconds(): BigInt { + let result = super.call( + "withdrawDelayTimeSeconds", + "withdrawDelayTimeSeconds():(uint256)", + [] + ); + + return result[0].toBigInt(); + } + + try_withdrawDelayTimeSeconds(): ethereum.CallResult { + let result = super.tryCall( + "withdrawDelayTimeSeconds", + "withdrawDelayTimeSeconds():(uint256)", + [] + ); + if (result.reverted) { + return new ethereum.CallResult(); + } + let value = result.value; + return ethereum.CallResult.fromValue(value[0].toBigInt()); + } +} + +export class ConstructorCall extends ethereum.Call { + get inputs(): ConstructorCall__Inputs { + return new ConstructorCall__Inputs(this); + } + + get outputs(): ConstructorCall__Outputs { + return new ConstructorCall__Outputs(this); + } +} + +export class ConstructorCall__Inputs { + _call: ConstructorCall; + + constructor(call: ConstructorCall) { + this._call = call; + } + + get _tellerV2(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get _smartCommitmentForwarder(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class ConstructorCall__Outputs { + _call: ConstructorCall; + + constructor(call: ConstructorCall) { + this._call = call; + } +} + +export class AcceptFundsForAcceptBidCall extends ethereum.Call { + get inputs(): AcceptFundsForAcceptBidCall__Inputs { + return new AcceptFundsForAcceptBidCall__Inputs(this); + } + + get outputs(): AcceptFundsForAcceptBidCall__Outputs { + return new AcceptFundsForAcceptBidCall__Outputs(this); + } +} + +export class AcceptFundsForAcceptBidCall__Inputs { + _call: AcceptFundsForAcceptBidCall; + + constructor(call: AcceptFundsForAcceptBidCall) { + this._call = call; + } + + get _borrower(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get _bidId(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } + + get _principalAmount(): BigInt { + return this._call.inputValues[2].value.toBigInt(); + } + + get _collateralAmount(): BigInt { + return this._call.inputValues[3].value.toBigInt(); + } + + get _collateralTokenAddress(): Address { + return this._call.inputValues[4].value.toAddress(); + } + + get _collateralTokenId(): BigInt { + return this._call.inputValues[5].value.toBigInt(); + } + + get _loanDuration(): BigInt { + return this._call.inputValues[6].value.toBigInt(); + } + + get _interestRate(): i32 { + return this._call.inputValues[7].value.toI32(); + } +} + +export class AcceptFundsForAcceptBidCall__Outputs { + _call: AcceptFundsForAcceptBidCall; + + constructor(call: AcceptFundsForAcceptBidCall) { + this._call = call; + } +} + +export class ApproveCall extends ethereum.Call { + get inputs(): ApproveCall__Inputs { + return new ApproveCall__Inputs(this); + } + + get outputs(): ApproveCall__Outputs { + return new ApproveCall__Outputs(this); + } +} + +export class ApproveCall__Inputs { + _call: ApproveCall; + + constructor(call: ApproveCall) { + this._call = call; + } + + get spender(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get amount(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } +} + +export class ApproveCall__Outputs { + _call: ApproveCall; + + constructor(call: ApproveCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class DecreaseAllowanceCall extends ethereum.Call { + get inputs(): DecreaseAllowanceCall__Inputs { + return new DecreaseAllowanceCall__Inputs(this); + } + + get outputs(): DecreaseAllowanceCall__Outputs { + return new DecreaseAllowanceCall__Outputs(this); + } +} + +export class DecreaseAllowanceCall__Inputs { + _call: DecreaseAllowanceCall; + + constructor(call: DecreaseAllowanceCall) { + this._call = call; + } + + get spender(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get subtractedValue(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } +} + +export class DecreaseAllowanceCall__Outputs { + _call: DecreaseAllowanceCall; + + constructor(call: DecreaseAllowanceCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class DepositCall extends ethereum.Call { + get inputs(): DepositCall__Inputs { + return new DepositCall__Inputs(this); + } + + get outputs(): DepositCall__Outputs { + return new DepositCall__Outputs(this); + } +} + +export class DepositCall__Inputs { + _call: DepositCall; + + constructor(call: DepositCall) { + this._call = call; + } + + get assets(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get receiver(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class DepositCall__Outputs { + _call: DepositCall; + + constructor(call: DepositCall) { + this._call = call; + } + + get shares(): BigInt { + return this._call.outputValues[0].value.toBigInt(); + } +} + +export class IncreaseAllowanceCall extends ethereum.Call { + get inputs(): IncreaseAllowanceCall__Inputs { + return new IncreaseAllowanceCall__Inputs(this); + } + + get outputs(): IncreaseAllowanceCall__Outputs { + return new IncreaseAllowanceCall__Outputs(this); + } +} + +export class IncreaseAllowanceCall__Inputs { + _call: IncreaseAllowanceCall; + + constructor(call: IncreaseAllowanceCall) { + this._call = call; + } + + get spender(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get addedValue(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } +} + +export class IncreaseAllowanceCall__Outputs { + _call: IncreaseAllowanceCall; + + constructor(call: IncreaseAllowanceCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class InitializeCall extends ethereum.Call { + get inputs(): InitializeCall__Inputs { + return new InitializeCall__Inputs(this); + } + + get outputs(): InitializeCall__Outputs { + return new InitializeCall__Outputs(this); + } +} + +export class InitializeCall__Inputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } + + get _commitmentGroupConfig(): InitializeCall_commitmentGroupConfigStruct { + return changetype( + this._call.inputValues[0].value.toTuple() + ); + } + + get _priceAdapter(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get _priceAdapterRoute(): Bytes { + return this._call.inputValues[2].value.toBytes(); + } +} + +export class InitializeCall__Outputs { + _call: InitializeCall; + + constructor(call: InitializeCall) { + this._call = call; + } +} + +export class InitializeCall_commitmentGroupConfigStruct extends ethereum.Tuple { + get principalTokenAddress(): Address { + return this[0].toAddress(); + } + + get collateralTokenAddress(): Address { + return this[1].toAddress(); + } + + get marketId(): BigInt { + return this[2].toBigInt(); + } + + get maxLoanDuration(): BigInt { + return this[3].toBigInt(); + } + + get interestRateLowerBound(): i32 { + return this[4].toI32(); + } + + get interestRateUpperBound(): i32 { + return this[5].toI32(); + } + + get liquidityThresholdPercent(): i32 { + return this[6].toI32(); + } + + get collateralRatio(): i32 { + return this[7].toI32(); + } +} + +export class LiquidateDefaultedLoanWithIncentiveCall extends ethereum.Call { + get inputs(): LiquidateDefaultedLoanWithIncentiveCall__Inputs { + return new LiquidateDefaultedLoanWithIncentiveCall__Inputs(this); + } + + get outputs(): LiquidateDefaultedLoanWithIncentiveCall__Outputs { + return new LiquidateDefaultedLoanWithIncentiveCall__Outputs(this); + } +} + +export class LiquidateDefaultedLoanWithIncentiveCall__Inputs { + _call: LiquidateDefaultedLoanWithIncentiveCall; + + constructor(call: LiquidateDefaultedLoanWithIncentiveCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get _tokenAmountDifference(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } +} + +export class LiquidateDefaultedLoanWithIncentiveCall__Outputs { + _call: LiquidateDefaultedLoanWithIncentiveCall; + + constructor(call: LiquidateDefaultedLoanWithIncentiveCall) { + this._call = call; + } +} + +export class MintCall extends ethereum.Call { + get inputs(): MintCall__Inputs { + return new MintCall__Inputs(this); + } + + get outputs(): MintCall__Outputs { + return new MintCall__Outputs(this); + } +} + +export class MintCall__Inputs { + _call: MintCall; + + constructor(call: MintCall) { + this._call = call; + } + + get shares(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get receiver(): Address { + return this._call.inputValues[1].value.toAddress(); + } +} + +export class MintCall__Outputs { + _call: MintCall; + + constructor(call: MintCall) { + this._call = call; + } + + get assets(): BigInt { + return this._call.outputValues[0].value.toBigInt(); + } +} + +export class PauseBorrowingCall extends ethereum.Call { + get inputs(): PauseBorrowingCall__Inputs { + return new PauseBorrowingCall__Inputs(this); + } + + get outputs(): PauseBorrowingCall__Outputs { + return new PauseBorrowingCall__Outputs(this); + } +} + +export class PauseBorrowingCall__Inputs { + _call: PauseBorrowingCall; + + constructor(call: PauseBorrowingCall) { + this._call = call; + } +} + +export class PauseBorrowingCall__Outputs { + _call: PauseBorrowingCall; + + constructor(call: PauseBorrowingCall) { + this._call = call; + } +} + +export class PauseLiquidationAuctionCall extends ethereum.Call { + get inputs(): PauseLiquidationAuctionCall__Inputs { + return new PauseLiquidationAuctionCall__Inputs(this); + } + + get outputs(): PauseLiquidationAuctionCall__Outputs { + return new PauseLiquidationAuctionCall__Outputs(this); + } +} + +export class PauseLiquidationAuctionCall__Inputs { + _call: PauseLiquidationAuctionCall; + + constructor(call: PauseLiquidationAuctionCall) { + this._call = call; + } +} + +export class PauseLiquidationAuctionCall__Outputs { + _call: PauseLiquidationAuctionCall; + + constructor(call: PauseLiquidationAuctionCall) { + this._call = call; + } +} + +export class PausePoolCall extends ethereum.Call { + get inputs(): PausePoolCall__Inputs { + return new PausePoolCall__Inputs(this); + } + + get outputs(): PausePoolCall__Outputs { + return new PausePoolCall__Outputs(this); + } +} + +export class PausePoolCall__Inputs { + _call: PausePoolCall; + + constructor(call: PausePoolCall) { + this._call = call; + } +} + +export class PausePoolCall__Outputs { + _call: PausePoolCall; + + constructor(call: PausePoolCall) { + this._call = call; + } +} + +export class RedeemCall extends ethereum.Call { + get inputs(): RedeemCall__Inputs { + return new RedeemCall__Inputs(this); + } + + get outputs(): RedeemCall__Outputs { + return new RedeemCall__Outputs(this); + } +} + +export class RedeemCall__Inputs { + _call: RedeemCall; + + constructor(call: RedeemCall) { + this._call = call; + } + + get shares(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get receiver(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get owner(): Address { + return this._call.inputValues[2].value.toAddress(); + } +} + +export class RedeemCall__Outputs { + _call: RedeemCall; + + constructor(call: RedeemCall) { + this._call = call; + } + + get assets(): BigInt { + return this._call.outputValues[0].value.toBigInt(); + } +} + +export class RenounceOwnershipCall extends ethereum.Call { + get inputs(): RenounceOwnershipCall__Inputs { + return new RenounceOwnershipCall__Inputs(this); + } + + get outputs(): RenounceOwnershipCall__Outputs { + return new RenounceOwnershipCall__Outputs(this); + } +} + +export class RenounceOwnershipCall__Inputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RenounceOwnershipCall__Outputs { + _call: RenounceOwnershipCall; + + constructor(call: RenounceOwnershipCall) { + this._call = call; + } +} + +export class RepayLoanCallbackCall extends ethereum.Call { + get inputs(): RepayLoanCallbackCall__Inputs { + return new RepayLoanCallbackCall__Inputs(this); + } + + get outputs(): RepayLoanCallbackCall__Outputs { + return new RepayLoanCallbackCall__Outputs(this); + } +} + +export class RepayLoanCallbackCall__Inputs { + _call: RepayLoanCallbackCall; + + constructor(call: RepayLoanCallbackCall) { + this._call = call; + } + + get _bidId(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get repayer(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get principalAmount(): BigInt { + return this._call.inputValues[2].value.toBigInt(); + } + + get interestAmount(): BigInt { + return this._call.inputValues[3].value.toBigInt(); + } +} + +export class RepayLoanCallbackCall__Outputs { + _call: RepayLoanCallbackCall; + + constructor(call: RepayLoanCallbackCall) { + this._call = call; + } +} + +export class SetWithdrawDelayTimeCall extends ethereum.Call { + get inputs(): SetWithdrawDelayTimeCall__Inputs { + return new SetWithdrawDelayTimeCall__Inputs(this); + } + + get outputs(): SetWithdrawDelayTimeCall__Outputs { + return new SetWithdrawDelayTimeCall__Outputs(this); + } +} + +export class SetWithdrawDelayTimeCall__Inputs { + _call: SetWithdrawDelayTimeCall; + + constructor(call: SetWithdrawDelayTimeCall) { + this._call = call; + } + + get _seconds(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class SetWithdrawDelayTimeCall__Outputs { + _call: SetWithdrawDelayTimeCall; + + constructor(call: SetWithdrawDelayTimeCall) { + this._call = call; + } +} + +export class TransferCall extends ethereum.Call { + get inputs(): TransferCall__Inputs { + return new TransferCall__Inputs(this); + } + + get outputs(): TransferCall__Outputs { + return new TransferCall__Outputs(this); + } +} + +export class TransferCall__Inputs { + _call: TransferCall; + + constructor(call: TransferCall) { + this._call = call; + } + + get to(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get amount(): BigInt { + return this._call.inputValues[1].value.toBigInt(); + } +} + +export class TransferCall__Outputs { + _call: TransferCall; + + constructor(call: TransferCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class TransferFromCall extends ethereum.Call { + get inputs(): TransferFromCall__Inputs { + return new TransferFromCall__Inputs(this); + } + + get outputs(): TransferFromCall__Outputs { + return new TransferFromCall__Outputs(this); + } +} + +export class TransferFromCall__Inputs { + _call: TransferFromCall; + + constructor(call: TransferFromCall) { + this._call = call; + } + + get from(): Address { + return this._call.inputValues[0].value.toAddress(); + } + + get to(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get amount(): BigInt { + return this._call.inputValues[2].value.toBigInt(); + } +} + +export class TransferFromCall__Outputs { + _call: TransferFromCall; + + constructor(call: TransferFromCall) { + this._call = call; + } + + get value0(): boolean { + return this._call.outputValues[0].value.toBoolean(); + } +} + +export class TransferOwnershipCall extends ethereum.Call { + get inputs(): TransferOwnershipCall__Inputs { + return new TransferOwnershipCall__Inputs(this); + } + + get outputs(): TransferOwnershipCall__Outputs { + return new TransferOwnershipCall__Outputs(this); + } +} + +export class TransferOwnershipCall__Inputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } + + get newOwner(): Address { + return this._call.inputValues[0].value.toAddress(); + } +} + +export class TransferOwnershipCall__Outputs { + _call: TransferOwnershipCall; + + constructor(call: TransferOwnershipCall) { + this._call = call; + } +} + +export class UnpauseBorrowingCall extends ethereum.Call { + get inputs(): UnpauseBorrowingCall__Inputs { + return new UnpauseBorrowingCall__Inputs(this); + } + + get outputs(): UnpauseBorrowingCall__Outputs { + return new UnpauseBorrowingCall__Outputs(this); + } +} + +export class UnpauseBorrowingCall__Inputs { + _call: UnpauseBorrowingCall; + + constructor(call: UnpauseBorrowingCall) { + this._call = call; + } +} + +export class UnpauseBorrowingCall__Outputs { + _call: UnpauseBorrowingCall; + + constructor(call: UnpauseBorrowingCall) { + this._call = call; + } +} + +export class UnpauseLiquidationAuctionCall extends ethereum.Call { + get inputs(): UnpauseLiquidationAuctionCall__Inputs { + return new UnpauseLiquidationAuctionCall__Inputs(this); + } + + get outputs(): UnpauseLiquidationAuctionCall__Outputs { + return new UnpauseLiquidationAuctionCall__Outputs(this); + } +} + +export class UnpauseLiquidationAuctionCall__Inputs { + _call: UnpauseLiquidationAuctionCall; + + constructor(call: UnpauseLiquidationAuctionCall) { + this._call = call; + } +} + +export class UnpauseLiquidationAuctionCall__Outputs { + _call: UnpauseLiquidationAuctionCall; + + constructor(call: UnpauseLiquidationAuctionCall) { + this._call = call; + } +} + +export class UnpausePoolCall extends ethereum.Call { + get inputs(): UnpausePoolCall__Inputs { + return new UnpausePoolCall__Inputs(this); + } + + get outputs(): UnpausePoolCall__Outputs { + return new UnpausePoolCall__Outputs(this); + } +} + +export class UnpausePoolCall__Inputs { + _call: UnpausePoolCall; + + constructor(call: UnpausePoolCall) { + this._call = call; + } +} + +export class UnpausePoolCall__Outputs { + _call: UnpausePoolCall; + + constructor(call: UnpausePoolCall) { + this._call = call; + } +} + +export class WithdrawCall extends ethereum.Call { + get inputs(): WithdrawCall__Inputs { + return new WithdrawCall__Inputs(this); + } + + get outputs(): WithdrawCall__Outputs { + return new WithdrawCall__Outputs(this); + } +} + +export class WithdrawCall__Inputs { + _call: WithdrawCall; + + constructor(call: WithdrawCall) { + this._call = call; + } + + get assets(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } + + get receiver(): Address { + return this._call.inputValues[1].value.toAddress(); + } + + get owner(): Address { + return this._call.inputValues[2].value.toAddress(); + } +} + +export class WithdrawCall__Outputs { + _call: WithdrawCall; + + constructor(call: WithdrawCall) { + this._call = call; + } + + get shares(): BigInt { + return this._call.outputValues[0].value.toBigInt(); + } +} + +export class WithdrawFromEscrowVaultCall extends ethereum.Call { + get inputs(): WithdrawFromEscrowVaultCall__Inputs { + return new WithdrawFromEscrowVaultCall__Inputs(this); + } + + get outputs(): WithdrawFromEscrowVaultCall__Outputs { + return new WithdrawFromEscrowVaultCall__Outputs(this); + } +} + +export class WithdrawFromEscrowVaultCall__Inputs { + _call: WithdrawFromEscrowVaultCall; + + constructor(call: WithdrawFromEscrowVaultCall) { + this._call = call; + } + + get _amount(): BigInt { + return this._call.inputValues[0].value.toBigInt(); + } +} + +export class WithdrawFromEscrowVaultCall__Outputs { + _call: WithdrawFromEscrowVaultCall; + + constructor(call: WithdrawFromEscrowVaultCall) { + this._call = call; + } +} diff --git a/packages/subgraph-pool-v3/package.json b/packages/subgraph-pool-v3/package.json new file mode 100644 index 000000000..2232924b0 --- /dev/null +++ b/packages/subgraph-pool-v3/package.json @@ -0,0 +1,57 @@ +{ + "name": "@teller-protocol/subgraph-pool-v3", + "license": "UNLICENSED", + "version": "0.1.0", + "scripts": { + "generate": "node scripts/generate-subgraph.js", + "codegen": " graph codegen", + "build": " graph build", + "deploy:prompt": "ts-node scripts/thegraph", + "create-local": "graph create --node http://localhost:8020/ teller-v2", + "remove-local": "graph remove --node http://localhost:8020/ teller-v2", + "reset-local": "yarn remove-local && yarn create-local", + "deploy-local": "graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 teller-v2", + "test": "yarn graph test", + "deploy_ormi": "bash -c 'source .env && graph deploy \"$0\" --node https://api.subgraph.migration.ormilabs.com/deploy --ipfs https://api.subgraph.migration.ormilabs.com/ipfs --deploy-key \"$ORMI_LABS_DEPLOY_KEY\"'", + "format": "eslint './src/**/*.ts' --fix", + "ts-node": "ts-node --project ./scripts/tsconfig.json" + }, + "dependencies": { + "mustache": "^4.2.0" + }, + "devDependencies": { + "@graphprotocol/graph-cli": "^0.58.0", + "@graphprotocol/graph-ts": "^0.31.0", + "@ledgerhq/hw-app-eth": "^6.34.0", + "@ledgerhq/hw-transport-node-hid": "^6.27.19", + "@types/node": "^20.4.5", + "@types/prompts": "^2.4.4", + "@types/semver": "^7.5.0", + "@types/uuid": "^9.0.2", + "@typescript-eslint/eslint-plugin": "^7.0.0", + "@typescript-eslint/parser": "^7.0.0", + "assemblyscript": "^0.27.1", + "async-mutex": "^0.4.0", + "axios": "^1.4.0", + "cleaners": "^0.3.16", + "cli-progress": "^3.12.0", + "eslint": "^8.56.0", + "eslint-config-prettier": "^8.3.0", + "eslint-config-standard-kit": "0.15.1", + "eslint-plugin-import": "^2.25.2", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^5.0.0", + "eslint-plugin-simple-import-sort": "^7.0.0", + "eslint-plugin-unused-imports": "^3.0.0", + "hbs-cli": "^1.4.1", + "json": "^11.0.0", + "matchstick-as": "^0.4.0", + "memlet": "^0.1.7", + "prompts": "^2.4.2", + "semver": "^7.5.4", + "ts-node": "^10.9.1", + "typescript": "^5.4.0", + "uuid": "^9.0.0", + "ws": "^8.13.0" + } +} diff --git a/packages/subgraph-pool-v3/scripts/generate-subgraph.js b/packages/subgraph-pool-v3/scripts/generate-subgraph.js new file mode 100644 index 000000000..c99cc493a --- /dev/null +++ b/packages/subgraph-pool-v3/scripts/generate-subgraph.js @@ -0,0 +1,41 @@ +const fs = require('fs'); +const mustache = require('mustache'); +const path = require('path'); + +// Get network from command line args or default to base +const network = process.argv[2] || 'base'; + +console.log(`Generating subgraph.yaml for network: ${network}`); + +// Read the template file +const templatePath = path.join(__dirname, '..', 'subgraph.template.yaml'); +const template = fs.readFileSync(templatePath, 'utf8'); + +// Read the network config +const configPath = path.join(__dirname, '..', 'config', `${network}.json`); + +if (!fs.existsSync(configPath)) { + console.error(`Config file not found for network: ${network}`); + process.exit(1); +} + +const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + +// Prepare template variables +const templateVars = { + network: config.network || network, + startblock: config.contracts?.factory?.block || 0, + lenderCommitmentGroupFactory: config.contracts?.factory?.address || '0x0000000000000000000000000000000000000000', + collateralManager: config.contracts?.collateralManager?.address || '0x0000000000000000000000000000000000000000' +}; + +console.log('Template variables:', templateVars); + +// Generate the subgraph.yaml +const output = mustache.render(template, templateVars); + +// Write the output +const outputPath = path.join(__dirname, '..', 'subgraph.yaml'); +fs.writeFileSync(outputPath, output); + +console.log(`Generated subgraph.yaml successfully!`); diff --git a/packages/subgraph-pool-v3/src/graphql.config.yml b/packages/subgraph-pool-v3/src/graphql.config.yml new file mode 100644 index 000000000..b169f5ee3 --- /dev/null +++ b/packages/subgraph-pool-v3/src/graphql.config.yml @@ -0,0 +1,18 @@ +schema: schema.introspection.graphql +extensions: + endpoints: + Base: + url: https://api.studio.thegraph.com/query/36377/tellerv2-poolsv3-base/version/latest + headers: + user-agent: JS GraphQL + introspect: true + ApeChain: + url: https://api.studio.thegraph.com/query/36377/tellerv2-poolsv3-apechain/version/latest + headers: + user-agent: JS GraphQL + introspect: true + Local GraphQL Endpoint: + url: http://localhost:8080/graphql + headers: + user-agent: JS GraphQL + introspect: true diff --git a/packages/subgraph-pool-v3/src/mappings/collateralManager.ts b/packages/subgraph-pool-v3/src/mappings/collateralManager.ts new file mode 100644 index 000000000..d60ab682e --- /dev/null +++ b/packages/subgraph-pool-v3/src/mappings/collateralManager.ts @@ -0,0 +1,50 @@ +import { CollateralWithdrawn } from "../../generated/CollateralManager/CollateralManager" +import { group_pool_metric, teller_bid } from "../../generated/schema" +import { BigInt, Address, log } from "@graphprotocol/graph-ts" + +export function handleCollateralWithdrawn(event: CollateralWithdrawn): void { + let bidId = event.params._bidId + let collateralType = event.params._type + let collateralAddress = event.params._collateralAddress + let amount = event.params._amount + let tokenId = event.params._tokenId + let recipient = event.params._recipient + + log.info("CollateralWithdrawn: bidId={}, type={}, collateralAddress={}, amount={}, tokenId={}, recipient={}", [ + bidId.toString(), + collateralType.toString(), + collateralAddress.toHexString(), + amount.toString(), + tokenId.toString(), + recipient.toHexString() + ]) + + // Load the teller_bid entity to find which pool this bid belongs to + let tellerBid = teller_bid.load(bidId.toString()) + + if (tellerBid == null) { + log.warning("CollateralWithdrawn: Could not find teller_bid for bidId={}", [bidId.toString()]) + return + } + + // Get the pool address from the teller_bid + let poolAddress = tellerBid.group_pool_address + + // Load the pool metric + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + + if (poolMetric == null) { + log.warning("CollateralWithdrawn: Could not find pool metric for pool={}", [poolAddress.toHexString()]) + return + } + + // Update the total collateral withdrawn for this pool + poolMetric.total_collateral_tokens_withdrawn = poolMetric.total_collateral_tokens_withdrawn.plus(amount) + + poolMetric.save() + + log.info("Updated pool {} - total_collateral_withdrawn: {}", [ + poolAddress.toHexString(), + poolMetric.total_collateral_tokens_withdrawn.toString() + ]) +} diff --git a/packages/subgraph-pool-v3/src/mappings/core.ts b/packages/subgraph-pool-v3/src/mappings/core.ts new file mode 100644 index 000000000..59dc5c9bf --- /dev/null +++ b/packages/subgraph-pool-v3/src/mappings/core.ts @@ -0,0 +1,463 @@ +import { + BorrowerAcceptedFunds, + Withdraw, + Deposit, + LoanRepaid, + DefaultedLoanLiquidated, + PoolInitialized +} from "../../generated/templates/Pool/Pool" +import { + group_borrower_accepted_funds, + group_earnings_withdrawn, + group_lender_added_principal, + group_loan_repaid, + group_defaulted_loan_liquidated, + group_pool_metric, + group_user_metric, + group_pool_bid, + teller_bid, + group_pool_metric_data_point_daily, + group_pool_metric_data_point_weekly +} from "../../generated/schema" +import { BigInt, Address, Bytes } from "@graphprotocol/graph-ts" + +// Constants for time calculations +const SECONDS_IN_DAY = BigInt.fromI32(86400) // 24 * 60 * 60 + +const SECONDS_IN_DAY_TWO = BigInt.fromI32(86400) + +const SECONDS_IN_WEEK = BigInt.fromI32(604800) // 7 * 24 * 60 * 60 + +function getDayIndex(timestamp: BigInt): BigInt { + return timestamp.div(SECONDS_IN_DAY) +} + +function getWeekIndex(timestamp: BigInt): BigInt { + return timestamp.div(SECONDS_IN_WEEK) +} + +function updateOrCreateDailyDataPoint(poolAddress: Address, blockNumber: BigInt, timestamp: BigInt): void { + let dayIndex = getDayIndex(timestamp) + let dailyId = poolAddress.toHexString() + "-" + dayIndex.toString() + + let dailyDataPoint = group_pool_metric_data_point_daily.load(dailyId) + if (dailyDataPoint == null) { + dailyDataPoint = new group_pool_metric_data_point_daily(dailyId) + dailyDataPoint.group_pool_address = poolAddress + dailyDataPoint.total_principal_tokens_committed = BigInt.fromI32(0) + dailyDataPoint.total_principal_tokens_withdrawn = BigInt.fromI32(0) + dailyDataPoint.total_collateral_tokens_deposited = BigInt.fromI32(0) + dailyDataPoint.total_collateral_tokens_withdrawn = BigInt.fromI32(0) + dailyDataPoint.total_principal_tokens_borrowed = BigInt.fromI32(0) + dailyDataPoint.total_principal_tokens_repaid = BigInt.fromI32(0) + dailyDataPoint.total_interest_collected = BigInt.fromI32(0) + dailyDataPoint.token_difference_from_liquidations = BigInt.fromI32(0) + } + + // Update with latest block info and current pool metric values + dailyDataPoint.block_number = blockNumber + dailyDataPoint.block_time = timestamp + + // Load current pool metric to get latest values + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + dailyDataPoint.total_principal_tokens_committed = poolMetric.total_principal_tokens_committed + dailyDataPoint.total_principal_tokens_withdrawn = poolMetric.total_principal_tokens_withdrawn + dailyDataPoint.total_collateral_tokens_deposited = poolMetric.total_collateral_tokens_deposited + dailyDataPoint.total_collateral_tokens_withdrawn = poolMetric.total_collateral_tokens_withdrawn + dailyDataPoint.total_principal_tokens_borrowed = poolMetric.total_principal_tokens_borrowed + dailyDataPoint.total_principal_tokens_repaid = poolMetric.total_principal_tokens_repaid + dailyDataPoint.total_interest_collected = poolMetric.total_interest_collected + dailyDataPoint.token_difference_from_liquidations = poolMetric.token_difference_from_liquidations + } + + dailyDataPoint.save() +} + +function updateOrCreateWeeklyDataPoint(poolAddress: Address, blockNumber: BigInt, timestamp: BigInt): void { + let weekIndex = getWeekIndex(timestamp) + let weeklyId = poolAddress.toHexString() + "-" + weekIndex.toString() + + let weeklyDataPoint = group_pool_metric_data_point_weekly.load(weeklyId) + if (weeklyDataPoint == null) { + weeklyDataPoint = new group_pool_metric_data_point_weekly(weeklyId) + weeklyDataPoint.group_pool_address = poolAddress + weeklyDataPoint.total_principal_tokens_committed = BigInt.fromI32(0) + weeklyDataPoint.total_principal_tokens_withdrawn = BigInt.fromI32(0) + weeklyDataPoint.total_collateral_tokens_deposited = BigInt.fromI32(0) + weeklyDataPoint.total_collateral_tokens_withdrawn = BigInt.fromI32(0) + weeklyDataPoint.total_principal_tokens_borrowed = BigInt.fromI32(0) + weeklyDataPoint.total_principal_tokens_repaid = BigInt.fromI32(0) + weeklyDataPoint.total_interest_collected = BigInt.fromI32(0) + weeklyDataPoint.token_difference_from_liquidations = BigInt.fromI32(0) + } + + // Update with latest block info and current pool metric values + weeklyDataPoint.block_number = blockNumber + weeklyDataPoint.block_time = timestamp + + // Load current pool metric to get latest values + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + weeklyDataPoint.total_principal_tokens_committed = poolMetric.total_principal_tokens_committed + weeklyDataPoint.total_principal_tokens_withdrawn = poolMetric.total_principal_tokens_withdrawn + weeklyDataPoint.total_collateral_tokens_deposited = poolMetric.total_collateral_tokens_deposited + weeklyDataPoint.total_collateral_tokens_withdrawn = poolMetric.total_collateral_tokens_withdrawn + weeklyDataPoint.total_principal_tokens_borrowed = poolMetric.total_principal_tokens_borrowed + weeklyDataPoint.total_principal_tokens_repaid = poolMetric.total_principal_tokens_repaid + weeklyDataPoint.total_interest_collected = poolMetric.total_interest_collected + weeklyDataPoint.token_difference_from_liquidations = poolMetric.token_difference_from_liquidations + } + + weeklyDataPoint.save() +} + + +function updatePoolMetric(poolAddress: Address, blockNumber: BigInt, timestamp: BigInt): void { + + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + + if (poolMetric == null) { + return + } + + // compute getPoolTotalEstimatedValue using existing data + let totalEstimatedValue = poolMetric.total_principal_tokens_committed + .minus(poolMetric.total_principal_tokens_withdrawn) + .plus(poolMetric.total_interest_collected) + + //compute getTotalPrincipalTokensOutstandingInActiveLoans using existing data + let totalOutstandingLoans = poolMetric.total_principal_tokens_borrowed + .minus(poolMetric.total_principal_tokens_repaid) + + //compute getPoolUtilizationRatio using existing data + let utilizationRatio = BigInt.fromI32(0) + if (totalEstimatedValue.gt(BigInt.fromI32(0))) { + utilizationRatio = totalOutstandingLoans + .times(BigInt.fromI32(10000)) + .div(totalEstimatedValue) + } + + //compute getMinInterestRate using utilization ratio and existing bounds + let interestRateRange = poolMetric.interest_rate_upper_bound.minus(poolMetric.interest_rate_lower_bound) + let minInterestRate = poolMetric.interest_rate_lower_bound + .plus(interestRateRange.times(utilizationRatio).div(BigInt.fromI32(10000))) + + poolMetric.current_min_interest_rate = minInterestRate + + poolMetric.save() +} + + +function getOrCreateUserMetric(userAddress: Address, poolAddress: Address): group_user_metric { + let id = poolAddress.toHexString() + "-" + userAddress.toHexString() + let userMetric = group_user_metric.load(id) + + if (userMetric == null) { + userMetric = new group_user_metric(id) + userMetric.user_address = userAddress + userMetric.group_pool_address = poolAddress + userMetric.total_principal_tokens_committed = BigInt.fromI32(0) + userMetric.total_principal_tokens_withdrawn = BigInt.fromI32(0) + userMetric.total_principal_tokens_borrowed = BigInt.fromI32(0) + userMetric.total_collateral_tokens_deposited = BigInt.fromI32(0) + userMetric.save() + } + + return userMetric +} + + + + + + +export function handleBorrowerAcceptedFunds(event: BorrowerAcceptedFunds): void { + let poolAddress = event.address + let borrower = event.params.borrower + let bidId = event.params.bidId + let principalAmount = event.params.principalAmount + let collateralAmount = event.params.collateralAmount + let interestRate = event.params.interestRate + let loanDuration = event.params.loanDuration + + // Create borrower accepted funds event entity + let eventEntity = new group_borrower_accepted_funds( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + eventEntity.evt_tx_hash = event.transaction.hash + eventEntity.evt_index = event.logIndex + eventEntity.evt_block_time = event.block.timestamp + eventEntity.evt_block_number = event.block.number + eventEntity.group_pool_address = poolAddress + eventEntity.bid_id = bidId + eventEntity.borrower = borrower + eventEntity.collateral_amount = collateralAmount + eventEntity.interest_rate = BigInt.fromI32(interestRate) + eventEntity.loan_duration = loanDuration + eventEntity.principal_amount = principalAmount + eventEntity.save() + + // Create or update pool bid entity + let bidEntity = new group_pool_bid(poolAddress.toHexString() + "-" + bidId.toString()) + bidEntity.group_pool_address = poolAddress + bidEntity.bid_id = bidId + bidEntity.borrower = borrower + bidEntity.collateral_amount = collateralAmount + bidEntity.principal_amount = principalAmount + bidEntity.save() + + let tellerBidEntity = new teller_bid( bidId.toString() ) + tellerBidEntity.group_pool_address = poolAddress + tellerBidEntity.bid_id = bidId + tellerBidEntity.borrower = borrower + tellerBidEntity.collateral_amount = collateralAmount + tellerBidEntity.principal_amount = principalAmount + tellerBidEntity.save() + + + + // Update pool metrics + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + poolMetric.total_principal_tokens_borrowed = poolMetric.total_principal_tokens_borrowed.plus(principalAmount) + poolMetric.total_collateral_tokens_deposited = poolMetric.total_collateral_tokens_deposited.plus(collateralAmount) + + poolMetric.save() + + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + } + + // Update user metrics + let userMetric = getOrCreateUserMetric(borrower, poolAddress) + userMetric.total_principal_tokens_borrowed = userMetric.total_principal_tokens_borrowed.plus(principalAmount) + userMetric.total_collateral_tokens_deposited = userMetric.total_collateral_tokens_deposited.plus(collateralAmount) + + userMetric.save() + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} + +export function handleWithdraw(event: Withdraw): void { + let poolAddress = event.address + let lender = event.params.caller + let recipient = event.params.receiver + let owner = event.params.owner + let amountPoolSharesTokens = event.params.shares + let principalTokensWithdrawn = event.params.assets + + + // Create earnings withdrawn event entity + let eventEntity = new group_earnings_withdrawn( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + eventEntity.evt_tx_hash = event.transaction.hash + eventEntity.evt_index = event.logIndex + eventEntity.evt_block_time = event.block.timestamp + eventEntity.evt_block_number = event.block.number + eventEntity.group_pool_address = poolAddress + eventEntity.amount_pool_shares_tokens = amountPoolSharesTokens + eventEntity.lender = lender + eventEntity.principal_tokens_withdrawn = principalTokensWithdrawn + eventEntity.recipient = recipient + eventEntity.save() + + // Update pool metrics + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + poolMetric.total_principal_tokens_withdrawn = poolMetric.total_principal_tokens_withdrawn.plus(principalTokensWithdrawn) + poolMetric.save() + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + + } + + // Update user metrics + let userMetric = getOrCreateUserMetric(lender, poolAddress) + userMetric.total_principal_tokens_withdrawn = userMetric.total_principal_tokens_withdrawn.plus(principalTokensWithdrawn) + userMetric.save() + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} + +export function handleDeposit(event: Deposit): void { + let poolAddress = event.address + let lender = event.params.caller + let owner = event.params.owner //not used for now + let amount = event.params.assets + let sharesAmount = event.params.shares + let sharesRecipient = event.params.caller + + // Create lender added principal event entity + let eventEntity = new group_lender_added_principal( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + eventEntity.evt_tx_hash = event.transaction.hash + eventEntity.evt_index = event.logIndex + eventEntity.evt_block_time = event.block.timestamp + eventEntity.evt_block_number = event.block.number + eventEntity.group_pool_address = poolAddress + eventEntity.amount = amount + eventEntity.lender = lender + eventEntity.shares_amount = sharesAmount + eventEntity.shares_recipient = sharesRecipient + eventEntity.save() + + // Update pool metrics + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + poolMetric.total_principal_tokens_committed = poolMetric.total_principal_tokens_committed.plus(amount) + poolMetric.save() + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + } + + // Update user metrics + let userMetric = getOrCreateUserMetric(lender, poolAddress) + userMetric.total_principal_tokens_committed = userMetric.total_principal_tokens_committed.plus(amount) + userMetric.save() + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} + +export function handleLoanRepaid(event: LoanRepaid): void { + let poolAddress = event.address + let bidId = event.params.bidId + let repayer = event.params.repayer + let principalAmount = event.params.principalAmount + let interestAmount = event.params.interestAmount + let totalPrincipalRepaid = event.params.totalPrincipalRepaid + let totalInterestCollected = event.params.totalInterestCollected + + // Create loan repaid event entity + let eventEntity = new group_loan_repaid( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + eventEntity.evt_tx_hash = event.transaction.hash + eventEntity.evt_index = event.logIndex + eventEntity.evt_block_time = event.block.timestamp + eventEntity.evt_block_number = event.block.number + eventEntity.group_pool_address = poolAddress + eventEntity.bid_id = bidId + eventEntity.interest_amount = interestAmount + eventEntity.principal_amount = principalAmount + eventEntity.repayer = repayer + eventEntity.total_interest_collected = totalInterestCollected + eventEntity.total_principal_repaid = totalPrincipalRepaid + eventEntity.save() + + // Update pool metrics + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + poolMetric.total_principal_tokens_repaid = poolMetric.total_principal_tokens_repaid.plus(principalAmount) + poolMetric.total_interest_collected = poolMetric.total_interest_collected.plus(interestAmount) + poolMetric.save() + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + } + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} + +export function handleLoanLiquidated(event: DefaultedLoanLiquidated): void { + let poolAddress = event.address + let bidId = event.params.bidId + let liquidator = event.params.liquidator + let amountDue = event.params.amountDue + let tokenAmountDifference = event.params.tokenAmountDifference + + // Create defaulted loan liquidated event entity + let eventEntity = new group_defaulted_loan_liquidated( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + eventEntity.evt_tx_hash = event.transaction.hash + eventEntity.evt_index = event.logIndex + eventEntity.evt_block_time = event.block.timestamp + eventEntity.evt_block_number = event.block.number + eventEntity.group_pool_address = poolAddress + eventEntity.amount_due = amountDue + eventEntity.bid_id = bidId + eventEntity.liquidator = liquidator + eventEntity.token_amount_difference = tokenAmountDifference + eventEntity.save() + + // Update pool metrics + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric != null) { + poolMetric.total_principal_tokens_repaid = poolMetric.total_principal_tokens_repaid.plus(amountDue) + poolMetric.total_principal_tokens_repaid_by_liquidation_auction = poolMetric.total_principal_tokens_repaid_by_liquidation_auction.plus(amountDue) + + poolMetric.token_difference_from_liquidations = poolMetric.token_difference_from_liquidations.plus(tokenAmountDifference) + poolMetric.save() + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + } + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} + +export function handlePoolInitialized(event: PoolInitialized): void { + let poolAddress = event.address + let principalTokenAddress = event.params.principalTokenAddress + let collateralTokenAddress = event.params.collateralTokenAddress + let marketId = event.params.marketId + let maxLoanDuration = event.params.maxLoanDuration + let interestRateLowerBound = event.params.interestRateLowerBound + let interestRateUpperBound = event.params.interestRateUpperBound + let liquidityThresholdPercent = event.params.liquidityThresholdPercent + let loanToValuePercent = event.params.loanToValuePercent + let poolSharesToken = event.address + + // Create or update pool metric with all initialization parameters + let poolMetric = group_pool_metric.load(poolAddress.toHexString()) + if (poolMetric == null) { + poolMetric = new group_pool_metric(poolAddress.toHexString()) + poolMetric.group_pool_address = poolAddress + poolMetric.created_at = event.block.timestamp + + // Initialize counters to zero + poolMetric.total_principal_tokens_committed = BigInt.fromI32(0) + poolMetric.total_principal_tokens_withdrawn = BigInt.fromI32(0) + poolMetric.total_principal_tokens_borrowed = BigInt.fromI32(0) + poolMetric.total_collateral_tokens_deposited = BigInt.fromI32(0) + poolMetric.total_collateral_tokens_withdrawn = BigInt.fromI32(0) + poolMetric.total_principal_tokens_repaid = BigInt.fromI32(0) + poolMetric.total_principal_tokens_repaid_by_liquidation_auction = BigInt.fromI32(0) + poolMetric.total_interest_collected = BigInt.fromI32(0) + poolMetric.token_difference_from_liquidations = BigInt.fromI32(0) + + // Set placeholder values for RPC fields - these will need to be filled from contract calls + poolMetric.teller_v2_address = Address.zero() + poolMetric.smart_commitment_forwarder_address = Address.zero() + poolMetric.current_min_interest_rate = BigInt.fromI32(0) + } + + // Set all parameters from PoolInitialized event + poolMetric.principal_token_address = principalTokenAddress + poolMetric.collateral_token_address = collateralTokenAddress + poolMetric.shares_token_address = poolSharesToken + poolMetric.market_id = marketId + poolMetric.max_loan_duration = maxLoanDuration + poolMetric.interest_rate_lower_bound = BigInt.fromI32(interestRateLowerBound) + poolMetric.interest_rate_upper_bound = BigInt.fromI32(interestRateUpperBound) + poolMetric.liquidity_threshold_percent = BigInt.fromI32(liquidityThresholdPercent) + poolMetric.collateral_ratio = BigInt.fromI32(loanToValuePercent) + poolMetric.save() + + updatePoolMetric( poolAddress, event.block.number, event.block.timestamp ); + + // Update daily and weekly data points + updateOrCreateDailyDataPoint(poolAddress, event.block.number, event.block.timestamp) + updateOrCreateWeeklyDataPoint(poolAddress, event.block.number, event.block.timestamp) +} diff --git a/packages/subgraph-pool-v3/src/mappings/factory.ts b/packages/subgraph-pool-v3/src/mappings/factory.ts new file mode 100644 index 000000000..c856aac04 --- /dev/null +++ b/packages/subgraph-pool-v3/src/mappings/factory.ts @@ -0,0 +1,55 @@ +import { DeployedLenderGroupContract } from "../../generated/Factory/Factory" +import { Pool as PoolTemplate } from "../../generated/templates" +import { group_pool_metric, factory_deployed_lender_group_contract } from "../../generated/schema" +import { BigInt, Address } from "@graphprotocol/graph-ts" + +export function handleLenderGroupDeployed(event: DeployedLenderGroupContract): void { + let groupContract = event.params.groupContract + + // Create the factory event entity + let factoryEvent = new factory_deployed_lender_group_contract( + event.transaction.hash.toHexString() + "-" + event.logIndex.toString() + ) + factoryEvent.evt_tx_hash = event.transaction.hash + factoryEvent.evt_index = event.logIndex + factoryEvent.evt_block_time = event.block.timestamp + factoryEvent.evt_block_number = event.block.number + factoryEvent.group_contract = groupContract + factoryEvent.save() + + // Create the pool metric entity for this new group + let poolMetric = new group_pool_metric(groupContract.toHexString()) + poolMetric.group_pool_address = groupContract + poolMetric.created_at = event.block.timestamp + + // Initialize all numeric fields to zero + poolMetric.market_id = BigInt.fromI32(0) + poolMetric.max_loan_duration = BigInt.fromI32(0) + poolMetric.interest_rate_upper_bound = BigInt.fromI32(0) + poolMetric.interest_rate_lower_bound = BigInt.fromI32(0) + poolMetric.current_min_interest_rate = BigInt.fromI32(0) + poolMetric.liquidity_threshold_percent = BigInt.fromI32(0) + poolMetric.collateral_ratio = BigInt.fromI32(0) + poolMetric.total_principal_tokens_committed = BigInt.fromI32(0) + poolMetric.total_principal_tokens_withdrawn = BigInt.fromI32(0) + poolMetric.total_principal_tokens_borrowed = BigInt.fromI32(0) + poolMetric.total_collateral_tokens_deposited = BigInt.fromI32(0) + poolMetric.total_collateral_tokens_withdrawn = BigInt.fromI32(0) + poolMetric.total_principal_tokens_repaid = BigInt.fromI32(0) + poolMetric.total_principal_tokens_repaid_by_liquidation_auction = BigInt.fromI32(0) + poolMetric.total_interest_collected = BigInt.fromI32(0) + poolMetric.token_difference_from_liquidations = BigInt.fromI32(0) + + + // Initialize address fields to zero address (will be populated by pool events) + poolMetric.principal_token_address = Address.zero() + poolMetric.collateral_token_address = Address.zero() + poolMetric.shares_token_address = Address.zero() + poolMetric.teller_v2_address = Address.zero() + poolMetric.smart_commitment_forwarder_address = Address.zero() + + poolMetric.save() + + // Create the dynamic data source template to start indexing this pool + PoolTemplate.create(groupContract) +} diff --git a/packages/subgraph-pool-v3/src/schema.graphql b/packages/subgraph-pool-v3/src/schema.graphql new file mode 100644 index 000000000..b39a8fad9 --- /dev/null +++ b/packages/subgraph-pool-v3/src/schema.graphql @@ -0,0 +1,324 @@ +type factory_admin_changed @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + new_admin: Bytes! + previous_admin: Bytes! +} +type factory_beacon_upgraded @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + beacon: Bytes! +} +type factory_deployed_lender_group_contract @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_contract: Bytes! +} +type factory_upgraded @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + implementation: Bytes! +} + + + + +type group_borrower_accepted_funds @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + bid_id: BigInt! + borrower: Bytes! + collateral_amount: BigInt! + interest_rate: BigInt! + loan_duration: BigInt! + principal_amount: BigInt! +} + +type group_lender_added_principal @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + amount: BigInt! + lender: Bytes! + shares_amount: BigInt! + shares_recipient: Bytes! +} +type group_earnings_withdrawn @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + amount_pool_shares_tokens: BigInt! + lender: Bytes! + principal_tokens_withdrawn: BigInt! + recipient: Bytes! +} +type group_defaulted_loan_liquidated @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + amount_due: BigInt! + bid_id: BigInt! + liquidator: Bytes! + token_amount_difference: BigInt! +} +type group_initialized @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + version: BigInt! +} + +type group_loan_repaid @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + bid_id: BigInt! + interest_amount: BigInt! + principal_amount: BigInt! + repayer: Bytes! + total_interest_collected: BigInt! + total_principal_repaid: BigInt! +} +type group_ownership_transferred @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + new_owner: Bytes! + previous_owner: Bytes! +} +type group_paused @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + account: Bytes! +} + +# use group pool metrics instead +type group_pool_initialized @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + collateral_token_address: Bytes! + interest_rate_lower_bound: BigInt! + interest_rate_upper_bound: BigInt! + liquidity_threshold_percent: BigInt! + loan_to_value_percent: BigInt! + market_id: BigInt! + max_loan_duration: BigInt! + pool_shares_token: Bytes! + principal_token_address: Bytes! +} +type group_unpaused @entity(immutable: true) { + id: ID! + evt_tx_hash: Bytes! + evt_index: BigInt! + evt_block_time: BigInt! + evt_block_number: BigInt! + group_pool_address: Bytes! + account: Bytes! +} + +type group_pool_bid @entity(immutable: true) { + id: ID! + group_pool_address: Bytes! + bid_id: BigInt! + borrower: Bytes! + collateral_amount: BigInt! + principal_amount: BigInt! +} + + + +type teller_bid @entity(immutable: true) { + id: ID! + group_pool_address: Bytes! + bid_id: BigInt! + borrower: Bytes! + collateral_amount: BigInt! + principal_amount: BigInt! +} + + +type group_pool_metric @entity(immutable: false) { + id: ID! #will be based on group pool address + group_pool_address: Bytes! + + created_at: BigInt! + + principal_token_address: Bytes! + collateral_token_address: Bytes! + shares_token_address: Bytes! + + # get these from RPC calls + + teller_v2_address: Bytes! + smart_commitment_forwarder_address: Bytes! + # --- + + market_id: BigInt! + + max_loan_duration : BigInt! + + interest_rate_upper_bound: BigInt! + interest_rate_lower_bound: BigInt! + + current_min_interest_rate: BigInt! + + + liquidity_threshold_percent: BigInt! + collateral_ratio: BigInt! #loan to value + + total_principal_tokens_committed: BigInt! + total_principal_tokens_withdrawn: BigInt! + + total_principal_tokens_borrowed: BigInt! + + total_collateral_tokens_deposited: BigInt! + total_collateral_tokens_withdrawn: BigInt! + + total_principal_tokens_repaid: BigInt! + total_principal_tokens_repaid_by_liquidation_auction: BigInt! + total_interest_collected: BigInt! + + token_difference_from_liquidations: BigInt! + + +} + + + + + +type group_pool_metric_data_point @entity(immutable: false) { + id: ID! #will be based on group pool address + group_pool_address: Bytes! + + block_number: BigInt! + block_time: BigInt + + + total_principal_tokens_committed: BigInt! + total_principal_tokens_withdrawn: BigInt! + + total_collateral_tokens_deposited: BigInt! + total_collateral_tokens_withdrawn: BigInt! + + total_principal_tokens_borrowed: BigInt! + total_principal_tokens_repaid: BigInt! + total_interest_collected: BigInt! + + token_difference_from_liquidations: BigInt! + +} + +type group_pool_metric_data_point_daily @entity(immutable: false) { + id: ID! #will be based on group pool address and day id + group_pool_address: Bytes! + + block_number: BigInt! + block_time: BigInt + + + total_principal_tokens_committed: BigInt! + total_principal_tokens_withdrawn: BigInt! + total_collateral_tokens_deposited: BigInt! + total_collateral_tokens_withdrawn: BigInt! + + total_principal_tokens_borrowed: BigInt! + total_principal_tokens_repaid: BigInt! + total_interest_collected: BigInt! + + + token_difference_from_liquidations: BigInt! + + +} + +type group_pool_metric_data_point_weekly @entity(immutable: false) { + id: ID! #will be based on group pool address and week id + group_pool_address: Bytes! + + block_number: BigInt! + block_time: BigInt + + + total_principal_tokens_committed: BigInt! + total_principal_tokens_withdrawn: BigInt! + + total_collateral_tokens_deposited: BigInt! + total_collateral_tokens_withdrawn: BigInt! + + total_principal_tokens_borrowed: BigInt! + total_principal_tokens_repaid: BigInt! + total_interest_collected: BigInt! + + token_difference_from_liquidations: BigInt! + + +} + + + +type group_user_metric @entity(immutable: false) { + id: ID! #will be based on group pool address and user lender address + + user_address: Bytes! + group_pool_address: Bytes! + + total_principal_tokens_committed: BigInt! + total_principal_tokens_withdrawn: BigInt! + + total_principal_tokens_borrowed: BigInt! + # total_collateral_tokens_escrowed: BigInt! + total_collateral_tokens_deposited: BigInt! + + + # shares_tokens_balance: BigInt! # need to track from erc20 driver + + # shares_balance_value: BigInt! # valued in principal tokens + # total_interest_earned: BigInt! # valued in principal tokens + + +} + +# also add borrower metrics ? diff --git a/packages/subgraph-pool-v3/subgraph.template.yaml b/packages/subgraph-pool-v3/subgraph.template.yaml new file mode 100644 index 000000000..af83a5481 --- /dev/null +++ b/packages/subgraph-pool-v3/subgraph.template.yaml @@ -0,0 +1,81 @@ +specVersion: 0.0.4 +description: Teller Protocol V3 Pools - Agnostic Oracle lending pools. +repository: https://github.com/teller-protocol/teller-protocol-v2 +schema: + file: ./src/schema.graphql +features: + - nonFatalErrors + - grafting +dataSources: + - kind: ethereum/contract + name: Factory + network: {{ network }} + source: + abi: Factory + address: "{{lenderCommitmentGroupFactory}}" + startBlock: {{ startblock }} + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/factory.ts + entities: + - Pool + abis: + - name: Factory + file: ./abis/Factory.json + eventHandlers: + - event: DeployedLenderGroupContract(indexed address) + handler: handleLenderGroupDeployed + - kind: ethereum/contract + name: CollateralManager + network: {{ network }} + source: + abi: CollateralManager + address: "{{collateralManager}}" + startBlock: {{ startblock }} + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/collateralManager.ts + entities: + - TellerBid + - GroupPoolMetric + abis: + - name: CollateralManager + file: ./abis/CollateralManager.json + eventHandlers: + - event: CollateralWithdrawn(uint256,uint8,address,uint256,uint256,address) + handler: handleCollateralWithdrawn +templates: + - kind: ethereum/contract + name: Pool + network: {{ network }} + source: + abi: Pool + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/core.ts + entities: + - Pool + abis: + - name: Pool + file: ./abis/PoolV3.json + - name: Factory + file: ./abis/Factory.json + eventHandlers: + - event: BorrowerAcceptedFunds(indexed address,indexed uint256,uint256,uint256,uint32,uint16) + handler: handleBorrowerAcceptedFunds + - event: Withdraw(indexed address,indexed address,indexed address,uint256,uint256) + handler: handleWithdraw + - event: Deposit(indexed address,indexed address,uint256,uint256) + handler: handleDeposit + - event: LoanRepaid(indexed uint256,indexed address,uint256,uint256,uint256,uint256) + handler: handleLoanRepaid + - event: DefaultedLoanLiquidated(indexed uint256,indexed address,uint256,int256) + handler: handleLoanLiquidated + - event: PoolInitialized(indexed address,indexed address,uint256,uint32,uint16,uint16,uint16,uint16) + handler: handlePoolInitialized diff --git a/packages/subgraph-pool-v3/subgraph.yaml b/packages/subgraph-pool-v3/subgraph.yaml new file mode 100644 index 000000000..416317826 --- /dev/null +++ b/packages/subgraph-pool-v3/subgraph.yaml @@ -0,0 +1,81 @@ +specVersion: 0.0.4 +description: Teller Protocol V3 Pools - Agnostic Oracle lending pools. +repository: https://github.com/teller-protocol/teller-protocol-v2 +schema: + file: ./src/schema.graphql +features: + - nonFatalErrors + - grafting +dataSources: + - kind: ethereum/contract + name: Factory + network: apechain + source: + abi: Factory + address: "0x26E2BD4F67136a7929DFE82BD6392633eb5610C2" + startBlock: 34211523 + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/factory.ts + entities: + - Pool + abis: + - name: Factory + file: ./abis/Factory.json + eventHandlers: + - event: DeployedLenderGroupContract(indexed address) + handler: handleLenderGroupDeployed + - kind: ethereum/contract + name: CollateralManager + network: apechain + source: + abi: CollateralManager + address: "0x90D08f8Df66dFdE93801783FF7A36876453DAE75" + startBlock: 34211523 + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/collateralManager.ts + entities: + - TellerBid + - GroupPoolMetric + abis: + - name: CollateralManager + file: ./abis/CollateralManager.json + eventHandlers: + - event: CollateralWithdrawn(uint256,uint8,address,uint256,uint256,address) + handler: handleCollateralWithdrawn +templates: + - kind: ethereum/contract + name: Pool + network: apechain + source: + abi: Pool + mapping: + kind: ethereum/events + apiVersion: 0.0.7 + language: wasm/assemblyscript + file: ./src/mappings/core.ts + entities: + - Pool + abis: + - name: Pool + file: ./abis/PoolV3.json + - name: Factory + file: ./abis/Factory.json + eventHandlers: + - event: BorrowerAcceptedFunds(indexed address,indexed uint256,uint256,uint256,uint32,uint16) + handler: handleBorrowerAcceptedFunds + - event: Withdraw(indexed address,indexed address,indexed address,uint256,uint256) + handler: handleWithdraw + - event: Deposit(indexed address,indexed address,uint256,uint256) + handler: handleDeposit + - event: LoanRepaid(indexed uint256,indexed address,uint256,uint256,uint256,uint256) + handler: handleLoanRepaid + - event: DefaultedLoanLiquidated(indexed uint256,indexed address,uint256,int256) + handler: handleLoanLiquidated + - event: PoolInitialized(indexed address,indexed address,uint256,uint32,uint16,uint16,uint16,uint16) + handler: handlePoolInitialized diff --git a/packages/subgraph-pool-v3/tsconfig.json b/packages/subgraph-pool-v3/tsconfig.json new file mode 100644 index 000000000..b4c3ca4ae --- /dev/null +++ b/packages/subgraph-pool-v3/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "assemblyscript/std/assembly.json", + "include": [ + "./src", + "./config", + "./tests" + ], + "exclude": [ + "./build", + "./generated", + "./abis", + "**/node_modules", + "node_modules" + ] +} diff --git a/yarn.lock b/yarn.lock index e4dd7c075..f767322df 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2527,6 +2527,47 @@ __metadata: languageName: unknown linkType: soft +"@teller-protocol/subgraph-pool-v3@workspace:packages/subgraph-pool-v3": + version: 0.0.0-use.local + resolution: "@teller-protocol/subgraph-pool-v3@workspace:packages/subgraph-pool-v3" + dependencies: + "@graphprotocol/graph-cli": ^0.58.0 + "@graphprotocol/graph-ts": ^0.31.0 + "@ledgerhq/hw-app-eth": ^6.34.0 + "@ledgerhq/hw-transport-node-hid": ^6.27.19 + "@types/node": ^20.4.5 + "@types/prompts": ^2.4.4 + "@types/semver": ^7.5.0 + "@types/uuid": ^9.0.2 + "@typescript-eslint/eslint-plugin": ^7.0.0 + "@typescript-eslint/parser": ^7.0.0 + assemblyscript: ^0.27.1 + async-mutex: ^0.4.0 + axios: ^1.4.0 + cleaners: ^0.3.16 + cli-progress: ^3.12.0 + eslint: ^8.56.0 + eslint-config-prettier: ^8.3.0 + eslint-config-standard-kit: 0.15.1 + eslint-plugin-import: ^2.25.2 + eslint-plugin-node: ^11.1.0 + eslint-plugin-prettier: ^5.0.0 + eslint-plugin-simple-import-sort: ^7.0.0 + eslint-plugin-unused-imports: ^3.0.0 + hbs-cli: ^1.4.1 + json: ^11.0.0 + matchstick-as: ^0.4.0 + memlet: ^0.1.7 + mustache: ^4.2.0 + prompts: ^2.4.2 + semver: ^7.5.4 + ts-node: ^10.9.1 + typescript: ^5.4.0 + uuid: ^9.0.0 + ws: ^8.13.0 + languageName: unknown + linkType: soft + "@teller-protocol/v2-contracts@workspace:packages/contracts": version: 0.0.0-use.local resolution: "@teller-protocol/v2-contracts@workspace:packages/contracts" From 62362bcc52f3d9116f5df107b5e90c230d3a2e6e Mon Sep 17 00:00:00 2001 From: Ethereumdegen Date: Mon, 2 Mar 2026 14:13:22 -0500 Subject: [PATCH 46/46] add apechain and bnb subgraphs --- packages/subgraph-pool-v3/package.json | 1 + packages/subgraph/config/apechain.json | 1 + packages/subgraph/config/bsc.json | 1 + 3 files changed, 3 insertions(+) create mode 100644 packages/subgraph/config/apechain.json create mode 100644 packages/subgraph/config/bsc.json diff --git a/packages/subgraph-pool-v3/package.json b/packages/subgraph-pool-v3/package.json index 2232924b0..8e904f83a 100644 --- a/packages/subgraph-pool-v3/package.json +++ b/packages/subgraph-pool-v3/package.json @@ -13,6 +13,7 @@ "deploy-local": "graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 teller-v2", "test": "yarn graph test", "deploy_ormi": "bash -c 'source .env && graph deploy \"$0\" --node https://api.subgraph.migration.ormilabs.com/deploy --ipfs https://api.subgraph.migration.ormilabs.com/ipfs --deploy-key \"$ORMI_LABS_DEPLOY_KEY\"'", + "deploy_ormi_apechain": "bash -c 'source .env && graph deploy \"$0\" --node https://api.subgraph.apechain.ormilabs.com/deploy --ipfs https://api.subgraph.apechain.ormilabs.com/ipfs --deploy-key \"$ORMI_LABS_APECHAIN_DEPLOY_KEY\"'", "format": "eslint './src/**/*.ts' --fix", "ts-node": "ts-node --project ./scripts/tsconfig.json" }, diff --git a/packages/subgraph/config/apechain.json b/packages/subgraph/config/apechain.json new file mode 100644 index 000000000..dea16d1b8 --- /dev/null +++ b/packages/subgraph/config/apechain.json @@ -0,0 +1 @@ +{"enabled":true,"name":"teller-v2-apechain","network":"apechain-mainnet","export_network_name":"apechain","product":"studio","studio":{"owner":"0x1A2bAA2257343119FB03FD448622456a0c4f2190","network":"mainnet"},"grafting":{"enabled":false},"block_handler":{"enabled":false,"block":"33944573"},"contracts":{"teller_v2":{"enabled":true,"address":"0x3AF8DB041fcaFA539C2c78f73aa209383ba703ed","block":"33944573"},"market_registry":{"enabled":true,"address":"0x0708480670BdE591e275B06Cd19EcaDFC93A1f16","block":"33944590"},"lender_commitment":{"enabled":false,"address":"0x0000000000000000000000000000000000000000","block":"33944573"},"lender_commitment_staging":{"enabled":false,"address":"0x0000000000000000000000000000000000000000","block":"33944573"},"lender_commitment_alpha":{"enabled":true,"address":"0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515","block":"33944592"},"collateral_manager":{"enabled":true,"address":"0x90D08f8Df66dFdE93801783FF7A36876453DAE75","block":"33944575"},"lender_manager":{"enabled":true,"address":"0x0AeeeD450EcCaFaA140222De43963B179B514540","block":"33944610"},"market_liquidity_rewards":{"enabled":true,"address":"0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D","block":"33944631"}}} \ No newline at end of file diff --git a/packages/subgraph/config/bsc.json b/packages/subgraph/config/bsc.json new file mode 100644 index 000000000..bf48a516d --- /dev/null +++ b/packages/subgraph/config/bsc.json @@ -0,0 +1 @@ +{"enabled":true,"name":"teller-v2-bsc","network":"bsc","export_network_name":"bsc","product":"studio","studio":{"owner":"0x1A2bAA2257343119FB03FD448622456a0c4f2190","network":"mainnet"},"grafting":{"enabled":false},"block_handler":{"enabled":false,"block":"81086249"},"contracts":{"teller_v2":{"enabled":true,"address":"0x90D08f8Df66dFdE93801783FF7A36876453DAE75","block":"81086249"},"market_registry":{"enabled":true,"address":"0xdb2Ba4a2b90c6670f240D59AfcBeb35cd9Edd515","block":"81086314"},"lender_commitment":{"enabled":false,"address":"0x0000000000000000000000000000000000000000","block":"81086249"},"lender_commitment_staging":{"enabled":false,"address":"0x0000000000000000000000000000000000000000","block":"81086249"},"lender_commitment_alpha":{"enabled":true,"address":"0xfDDcEc68cfa40c38Faf05F918484fC416a221BFF","block":"81087490"},"collateral_manager":{"enabled":true,"address":"0x9D55Cf23D26a8C17670bb8Ee25D58481ff7aD295","block":"81086266"},"lender_manager":{"enabled":true,"address":"0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB","block":"81086350"},"market_liquidity_rewards":{"enabled":true,"address":"0x7Ff158DcD62C4E112f374F14fF25C735E8E4684D","block":"81088817"}}} \ No newline at end of file