Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Advanced mode: Intended for advanced users or developers and will display all Internal Transactions including zero value transfers.
Latest 25 internal transactions (View All)
Advanced mode:
Parent Transaction Hash | Block | From | To | ||||
---|---|---|---|---|---|---|---|
8104728 | 57 days ago | 0 ETH | |||||
8096573 | 57 days ago | 0 ETH | |||||
8095742 | 57 days ago | 0 ETH | |||||
8095742 | 57 days ago | 0 ETH | |||||
8095742 | 57 days ago | 0 ETH | |||||
8095742 | 57 days ago | 0 ETH | |||||
8095742 | 57 days ago | 0 ETH | |||||
8011429 | 58 days ago | 0 ETH | |||||
8011429 | 58 days ago | 0 ETH | |||||
8011429 | 58 days ago | 0 ETH | |||||
8011429 | 58 days ago | 0 ETH | |||||
8011429 | 58 days ago | 0 ETH | |||||
8011330 | 58 days ago | 0 ETH | |||||
8011277 | 58 days ago | 0 ETH | |||||
8011252 | 58 days ago | 0 ETH | |||||
8011234 | 58 days ago | 0 ETH | |||||
8011161 | 58 days ago | 0 ETH | |||||
8011161 | 58 days ago | 0 ETH | |||||
8011161 | 58 days ago | 0 ETH | |||||
7776940 | 60 days ago | 0 ETH | |||||
7776493 | 60 days ago | 0 ETH | |||||
7686359 | 61 days ago | 0 ETH | |||||
7623212 | 62 days ago | 0 ETH | |||||
7623011 | 62 days ago | 0 ETH | |||||
7623011 | 62 days ago | 0 ETH |
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
LenderCommitmentGroup_Pool_V2
Compiler Version
v0.8.11+commit.d7f03943
Optimization Enabled:
Yes with 200 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// 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/uniswap/IUniswapV3Factory.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 UNISWAP_V3_FACTORY; 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; 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 _uniswapV3Factory ) OracleProtectedChild(_smartCommitmentForwarder) { TELLER_V2 = _tellerV2; SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder; UNISWAP_V3_FACTORY = _uniswapV3Factory; } /** * @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, 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"); 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) ; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Tree proofs. * * The tree and the proofs can be generated using our * https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. * You will find a quickstart guide in the readme. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. * OpenZeppelin's JavaScript library generates merkle trees that are safe * against this attack out of the box. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata( bytes32[] calldata proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "../Types.sol"; import "../interfaces/IEAS.sol"; import "../interfaces/IASRegistry.sol"; /** * @title TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service */ contract TellerAS is IEAS { error AccessDenied(); error AlreadyRevoked(); error InvalidAttestation(); error InvalidExpirationTime(); error InvalidOffset(); error InvalidRegistry(); error InvalidSchema(); error InvalidVerifier(); error NotFound(); error NotPayable(); string public constant VERSION = "0.8"; // A terminator used when concatenating and hashing multiple fields. string private constant HASH_TERMINATOR = "@"; // The AS global registry. IASRegistry private immutable _asRegistry; // The EIP712 verifier used to verify signed attestations. IEASEIP712Verifier private immutable _eip712Verifier; // A mapping between attestations and their related attestations. mapping(bytes32 => bytes32[]) private _relatedAttestations; // A mapping between an account and its received attestations. mapping(address => mapping(bytes32 => bytes32[])) private _receivedAttestations; // A mapping between an account and its sent attestations. mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations; // A mapping between a schema and its attestations. mapping(bytes32 => bytes32[]) private _schemaAttestations; // The global mapping between attestations and their UUIDs. mapping(bytes32 => Attestation) private _db; // The global counter for the total number of attestations. uint256 private _attestationsCount; bytes32 private _lastUUID; /** * @dev Creates a new EAS instance. * * @param registry The address of the global AS registry. * @param verifier The address of the EIP712 verifier. */ constructor(IASRegistry registry, IEASEIP712Verifier verifier) { if (address(registry) == address(0x0)) { revert InvalidRegistry(); } if (address(verifier) == address(0x0)) { revert InvalidVerifier(); } _asRegistry = registry; _eip712Verifier = verifier; } /** * @inheritdoc IEAS */ function getASRegistry() external view override returns (IASRegistry) { return _asRegistry; } /** * @inheritdoc IEAS */ function getEIP712Verifier() external view override returns (IEASEIP712Verifier) { return _eip712Verifier; } /** * @inheritdoc IEAS */ function getAttestationsCount() external view override returns (uint256) { return _attestationsCount; } /** * @inheritdoc IEAS */ function attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data ) public payable virtual override returns (bytes32) { return _attest( recipient, schema, expirationTime, refUUID, data, msg.sender ); } /** * @inheritdoc IEAS */ function attestByDelegation( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester, uint8 v, bytes32 r, bytes32 s ) public payable virtual override returns (bytes32) { _eip712Verifier.attest( recipient, schema, expirationTime, refUUID, data, attester, v, r, s ); return _attest(recipient, schema, expirationTime, refUUID, data, attester); } /** * @inheritdoc IEAS */ function revoke(bytes32 uuid) public virtual override { return _revoke(uuid, msg.sender); } /** * @inheritdoc IEAS */ function revokeByDelegation( bytes32 uuid, address attester, uint8 v, bytes32 r, bytes32 s ) public virtual override { _eip712Verifier.revoke(uuid, attester, v, r, s); _revoke(uuid, attester); } /** * @inheritdoc IEAS */ function getAttestation(bytes32 uuid) external view override returns (Attestation memory) { return _db[uuid]; } /** * @inheritdoc IEAS */ function isAttestationValid(bytes32 uuid) public view override returns (bool) { return _db[uuid].uuid != 0; } /** * @inheritdoc IEAS */ function isAttestationActive(bytes32 uuid) public view virtual override returns (bool) { return isAttestationValid(uuid) && _db[uuid].expirationTime >= block.timestamp && _db[uuid].revocationTime == 0; } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDs( address recipient, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view override returns (bytes32[] memory) { return _sliceUUIDs( _receivedAttestations[recipient][schema], start, length, reverseOrder ); } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema) external view override returns (uint256) { return _receivedAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getSentAttestationUUIDs( address attester, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view override returns (bytes32[] memory) { return _sliceUUIDs( _sentAttestations[attester][schema], start, length, reverseOrder ); } /** * @inheritdoc IEAS */ function getSentAttestationUUIDsCount(address recipient, bytes32 schema) external view override returns (uint256) { return _sentAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDs( bytes32 uuid, uint256 start, uint256 length, bool reverseOrder ) external view override returns (bytes32[] memory) { return _sliceUUIDs( _relatedAttestations[uuid], start, length, reverseOrder ); } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDsCount(bytes32 uuid) external view override returns (uint256) { return _relatedAttestations[uuid].length; } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDs( bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view override returns (bytes32[] memory) { return _sliceUUIDs( _schemaAttestations[schema], start, length, reverseOrder ); } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDsCount(bytes32 schema) external view override returns (uint256) { return _schemaAttestations[schema].length; } /** * @dev Attests to a specific AS. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * @param attester The attesting account. * * @return The UUID of the new attestation. */ function _attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester ) private returns (bytes32) { if (expirationTime <= block.timestamp) { revert InvalidExpirationTime(); } IASRegistry.ASRecord memory asRecord = _asRegistry.getAS(schema); if (asRecord.uuid == EMPTY_UUID) { revert InvalidSchema(); } IASResolver resolver = asRecord.resolver; if (address(resolver) != address(0x0)) { if (msg.value != 0 && !resolver.isPayable()) { revert NotPayable(); } if ( !resolver.resolve{ value: msg.value }( recipient, asRecord.schema, data, expirationTime, attester ) ) { revert InvalidAttestation(); } } Attestation memory attestation = Attestation({ uuid: EMPTY_UUID, schema: schema, recipient: recipient, attester: attester, time: block.timestamp, expirationTime: expirationTime, revocationTime: 0, refUUID: refUUID, data: data }); _lastUUID = _getUUID(attestation); attestation.uuid = _lastUUID; _receivedAttestations[recipient][schema].push(_lastUUID); _sentAttestations[attester][schema].push(_lastUUID); _schemaAttestations[schema].push(_lastUUID); _db[_lastUUID] = attestation; _attestationsCount++; if (refUUID != 0) { if (!isAttestationValid(refUUID)) { revert NotFound(); } _relatedAttestations[refUUID].push(_lastUUID); } emit Attested(recipient, attester, _lastUUID, schema); return _lastUUID; } function getLastUUID() external view returns (bytes32) { return _lastUUID; } /** * @dev Revokes an existing attestation to a specific AS. * * @param uuid The UUID of the attestation to revoke. * @param attester The attesting account. */ function _revoke(bytes32 uuid, address attester) private { Attestation storage attestation = _db[uuid]; if (attestation.uuid == EMPTY_UUID) { revert NotFound(); } if (attestation.attester != attester) { revert AccessDenied(); } if (attestation.revocationTime != 0) { revert AlreadyRevoked(); } attestation.revocationTime = block.timestamp; emit Revoked(attestation.recipient, attester, uuid, attestation.schema); } /** * @dev Calculates a UUID for a given attestation. * * @param attestation The input attestation. * * @return Attestation UUID. */ function _getUUID(Attestation memory attestation) private view returns (bytes32) { return keccak256( abi.encodePacked( attestation.schema, attestation.recipient, attestation.attester, attestation.time, attestation.expirationTime, attestation.data, HASH_TERMINATOR, _attestationsCount ) ); } /** * @dev Returns a slice in an array of attestation UUIDs. * * @param uuids The array of attestation UUIDs. * @param start The offset to start from. * @param length The number of total members to retrieve. * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse. * * @return An array of attestation UUIDs. */ function _sliceUUIDs( bytes32[] memory uuids, uint256 start, uint256 length, bool reverseOrder ) private pure returns (bytes32[] memory) { uint256 attestationsLength = uuids.length; if (attestationsLength == 0) { return new bytes32[](0); } if (start >= attestationsLength) { revert InvalidOffset(); } uint256 len = length; if (attestationsLength < start + length) { len = attestationsLength - start; } bytes32[] memory res = new bytes32[](len); for (uint256 i = 0; i < len; ++i) { res[i] = uuids[ reverseOrder ? attestationsLength - (start + i + 1) : start + i ]; } return res; } }
// SPDX-Licence-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; enum CollateralType { ERC20, ERC721, ERC1155 } struct Collateral { CollateralType _collateralType; uint256 _amount; uint256 _tokenId; address _collateralAddress; } interface ICollateralEscrowV1 { /** * @notice Deposits a collateral asset into the escrow. * @param _collateralType The type of collateral asset to deposit (ERC721, ERC1155). * @param _collateralAddress The address of the collateral token.i feel * @param _amount The amount to deposit. */ function depositAsset( CollateralType _collateralType, address _collateralAddress, uint256 _amount, uint256 _tokenId ) external payable; /** * @notice Withdraws a collateral asset from the escrow. * @param _collateralAddress The address of the collateral contract. * @param _amount The amount to withdraw. * @param _recipient The address to send the assets to. */ function withdraw( address _collateralAddress, uint256 _amount, address _recipient ) external; function withdrawDustTokens( address _tokenAddress, uint256 _amount, address _recipient ) external; function getBid() external view returns (uint256); function initialize(uint256 _bidId) external; }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "./IASResolver.sol"; /** * @title The global AS registry interface. */ interface IASRegistry { /** * @title A struct representing a record for a submitted AS (Attestation Schema). */ struct ASRecord { // A unique identifier of the AS. bytes32 uuid; // Optional schema resolver. IASResolver resolver; // Auto-incrementing index for reference, assigned by the registry itself. uint256 index; // Custom specification of the AS (e.g., an ABI). bytes schema; } /** * @dev Triggered when a new AS has been registered * * @param uuid The AS UUID. * @param index The AS index. * @param schema The AS schema. * @param resolver An optional AS schema resolver. * @param attester The address of the account used to register the AS. */ event Registered( bytes32 indexed uuid, uint256 indexed index, bytes schema, IASResolver resolver, address attester ); /** * @dev Submits and reserve a new AS * * @param schema The AS data schema. * @param resolver An optional AS schema resolver. * * @return The UUID of the new AS. */ function register(bytes calldata schema, IASResolver resolver) external returns (bytes32); /** * @dev Returns an existing AS by UUID * * @param uuid The UUID of the AS to retrieve. * * @return The AS data members. */ function getAS(bytes32 uuid) external view returns (ASRecord memory); /** * @dev Returns the global counter for the total number of attestations * * @return The global counter for the total number of attestations. */ function getASCount() external view returns (uint256); }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT /** * @title The interface of an optional AS resolver. */ interface IASResolver { /** * @dev Returns whether the resolver supports ETH transfers */ function isPayable() external pure returns (bool); /** * @dev Resolves an attestation and verifier whether its data conforms to the spec. * * @param recipient The recipient of the attestation. * @param schema The AS data schema. * @param data The actual attestation data. * @param expirationTime The expiration time of the attestation. * @param msgSender The sender of the original attestation message. * * @return Whether the data is valid according to the scheme. */ function resolve( address recipient, bytes calldata schema, bytes calldata data, uint256 expirationTime, address msgSender ) external payable returns (bool); }
// SPDX-Licence-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import { Collateral } from "./escrow/ICollateralEscrowV1.sol"; interface ICollateralManager { /** * @notice Checks the validity of a borrower's collateral balance. * @param _bidId The id of the associated bid. * @param _collateralInfo Additional information about the collateral asset. * @return validation_ Boolean indicating if the collateral balance was validated. */ function commitCollateral( uint256 _bidId, Collateral[] calldata _collateralInfo ) external returns (bool validation_); /** * @notice Checks the validity of a borrower's collateral balance and commits it to a bid. * @param _bidId The id of the associated bid. * @param _collateralInfo Additional information about the collateral asset. * @return validation_ Boolean indicating if the collateral balance was validated. */ function commitCollateral( uint256 _bidId, Collateral calldata _collateralInfo ) external returns (bool validation_); function checkBalances( address _borrowerAddress, Collateral[] calldata _collateralInfo ) external returns (bool validated_, bool[] memory checks_); /** * @notice Deploys a new collateral escrow. * @param _bidId The associated bidId of the collateral escrow. */ function deployAndDeposit(uint256 _bidId) external; /** * @notice Gets the address of a deployed escrow. * @notice _bidId The bidId to return the escrow for. * @return The address of the escrow. */ function getEscrow(uint256 _bidId) external view returns (address); /** * @notice Gets the collateral info for a given bid id. * @param _bidId The bidId to return the collateral info for. * @return The stored collateral info. */ function getCollateralInfo(uint256 _bidId) external view returns (Collateral[] memory); function getCollateralAmount(uint256 _bidId, address collateralAssetAddress) external view returns (uint256 _amount); /** * @notice Withdraws deposited collateral from the created escrow of a bid. * @param _bidId The id of the bid to withdraw collateral for. */ function withdraw(uint256 _bidId) external; /** * @notice Re-checks the validity of a borrower's collateral balance committed to a bid. * @param _bidId The id of the associated bid. * @return validation_ Boolean indicating if the collateral balance was validated. */ function revalidateCollateral(uint256 _bidId) external returns (bool); /** * @notice Sends the deposited collateral to a lender of a bid. * @notice Can only be called by the protocol. * @param _bidId The id of the liquidated bid. */ function lenderClaimCollateral(uint256 _bidId) external; /** * @notice Sends the deposited collateral to a lender of a bid. * @notice Can only be called by the protocol. * @param _bidId The id of the liquidated bid. * @param _collateralRecipient the address that will receive the collateral */ function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external; /** * @notice Sends the deposited collateral to a liquidator of a bid. * @notice Can only be called by the protocol. * @param _bidId The id of the liquidated bid. * @param _liquidatorAddress The address of the liquidator to send the collateral to. */ function liquidateCollateral(uint256 _bidId, address _liquidatorAddress) external; }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "./IASRegistry.sol"; import "./IEASEIP712Verifier.sol"; /** * @title EAS - Ethereum Attestation Service interface */ interface IEAS { /** * @dev A struct representing a single attestation. */ struct Attestation { // A unique identifier of the attestation. bytes32 uuid; // A unique identifier of the AS. bytes32 schema; // The recipient of the attestation. address recipient; // The attester/sender of the attestation. address attester; // The time when the attestation was created (Unix timestamp). uint256 time; // The time when the attestation expires (Unix timestamp). uint256 expirationTime; // The time when the attestation was revoked (Unix timestamp). uint256 revocationTime; // The UUID of the related attestation. bytes32 refUUID; // Custom attestation data. bytes data; } /** * @dev Triggered when an attestation has been made. * * @param recipient The recipient of the attestation. * @param attester The attesting account. * @param uuid The UUID the revoked attestation. * @param schema The UUID of the AS. */ event Attested( address indexed recipient, address indexed attester, bytes32 uuid, bytes32 indexed schema ); /** * @dev Triggered when an attestation has been revoked. * * @param recipient The recipient of the attestation. * @param attester The attesting account. * @param schema The UUID of the AS. * @param uuid The UUID the revoked attestation. */ event Revoked( address indexed recipient, address indexed attester, bytes32 uuid, bytes32 indexed schema ); /** * @dev Returns the address of the AS global registry. * * @return The address of the AS global registry. */ function getASRegistry() external view returns (IASRegistry); /** * @dev Returns the address of the EIP712 verifier used to verify signed attestations. * * @return The address of the EIP712 verifier used to verify signed attestations. */ function getEIP712Verifier() external view returns (IEASEIP712Verifier); /** * @dev Returns the global counter for the total number of attestations. * * @return The global counter for the total number of attestations. */ function getAttestationsCount() external view returns (uint256); /** * @dev Attests to a specific AS. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * * @return The UUID of the new attestation. */ function attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data ) external payable returns (bytes32); /** * @dev Attests to a specific AS using a provided EIP712 signature. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * @param attester The attesting account. * @param v The recovery ID. * @param r The x-coordinate of the nonce R. * @param s The signature data. * * @return The UUID of the new attestation. */ function attestByDelegation( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester, uint8 v, bytes32 r, bytes32 s ) external payable returns (bytes32); /** * @dev Revokes an existing attestation to a specific AS. * * @param uuid The UUID of the attestation to revoke. */ function revoke(bytes32 uuid) external; /** * @dev Attests to a specific AS using a provided EIP712 signature. * * @param uuid The UUID of the attestation to revoke. * @param attester The attesting account. * @param v The recovery ID. * @param r The x-coordinate of the nonce R. * @param s The signature data. */ function revokeByDelegation( bytes32 uuid, address attester, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns an existing attestation by UUID. * * @param uuid The UUID of the attestation to retrieve. * * @return The attestation data members. */ function getAttestation(bytes32 uuid) external view returns (Attestation memory); /** * @dev Checks whether an attestation exists. * * @param uuid The UUID of the attestation to retrieve. * * @return Whether an attestation exists. */ function isAttestationValid(bytes32 uuid) external view returns (bool); /** * @dev Checks whether an attestation is active. * * @param uuid The UUID of the attestation to retrieve. * * @return Whether an attestation is active. */ function isAttestationActive(bytes32 uuid) external view returns (bool); /** * @dev Returns all received attestation UUIDs. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param start The offset to start from. * @param length The number of total members to retrieve. * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse. * * @return An array of attestation UUIDs. */ function getReceivedAttestationUUIDs( address recipient, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory); /** * @dev Returns the number of received attestation UUIDs. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * * @return The number of attestations. */ function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256); /** * @dev Returns all sent attestation UUIDs. * * @param attester The attesting account. * @param schema The UUID of the AS. * @param start The offset to start from. * @param length The number of total members to retrieve. * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse. * * @return An array of attestation UUIDs. */ function getSentAttestationUUIDs( address attester, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory); /** * @dev Returns the number of sent attestation UUIDs. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * * @return The number of attestations. */ function getSentAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256); /** * @dev Returns all attestations related to a specific attestation. * * @param uuid The UUID of the attestation to retrieve. * @param start The offset to start from. * @param length The number of total members to retrieve. * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse. * * @return An array of attestation UUIDs. */ function getRelatedAttestationUUIDs( bytes32 uuid, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory); /** * @dev Returns the number of related attestation UUIDs. * * @param uuid The UUID of the attestation to retrieve. * * @return The number of related attestations. */ function getRelatedAttestationUUIDsCount(bytes32 uuid) external view returns (uint256); /** * @dev Returns all per-schema attestation UUIDs. * * @param schema The UUID of the AS. * @param start The offset to start from. * @param length The number of total members to retrieve. * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse. * * @return An array of attestation UUIDs. */ function getSchemaAttestationUUIDs( bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory); /** * @dev Returns the number of per-schema attestation UUIDs. * * @param schema The UUID of the AS. * * @return The number of attestations. */ function getSchemaAttestationUUIDsCount(bytes32 schema) external view returns (uint256); }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT /** * @title EIP712 typed signatures verifier for EAS delegated attestations interface. */ interface IEASEIP712Verifier { /** * @dev Returns the current nonce per-account. * * @param account The requested accunt. * * @return The current nonce. */ function getNonce(address account) external view returns (uint256); /** * @dev Verifies signed attestation. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * @param attester The attesting account. * @param v The recovery ID. * @param r The x-coordinate of the nonce R. * @param s The signature data. */ function attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Verifies signed revocations. * * @param uuid The UUID of the attestation to revoke. * @param attester The attesting account. * @param v The recovery ID. * @param r The x-coordinate of the nonce R. * @param s The signature data. */ function revoke( bytes32 uuid, address attester, uint8 v, bytes32 r, bytes32 s ) external; }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT interface IERC4626 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ /** * @dev Emitted when assets are deposited into the vault. * @param caller The caller who deposited the assets. * @param owner The owner who will receive the shares. * @param assets The amount of assets deposited. * @param shares The amount of shares minted. */ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); /** * @dev Emitted when shares are withdrawn from the vault. * @param caller The caller who withdrew the assets. * @param receiver The receiver of the assets. * @param owner The owner whose shares were burned. * @param assets The amount of assets withdrawn. * @param shares The amount of shares burned. */ event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /*////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ /** * @dev Returns the address of the underlying token used for the vault. * @return The address of the underlying asset token. */ function asset() external view returns (address); /*////////////////////////////////////////////////////////////// DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /** * @dev Deposits assets into the vault and mints shares to the receiver. * @param assets The amount of assets to deposit. * @param receiver The address that will receive the shares. * @return shares The amount of shares minted. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @dev Mints shares to the receiver by depositing exactly amount of assets. * @param shares The amount of shares to mint. * @param receiver The address that will receive the shares. * @return assets The amount of assets deposited. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @dev Withdraws assets from the vault to the receiver by burning shares from owner. * @param assets The amount of assets to withdraw. * @param receiver The address that will receive the assets. * @param owner The address whose shares will be burned. * @return shares The amount of shares burned. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); /** * @dev Burns shares from owner and sends exactly assets to receiver. * @param shares The amount of shares to burn. * @param receiver The address that will receive the assets. * @param owner The address whose shares will be burned. * @return assets The amount of assets sent to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); /*////////////////////////////////////////////////////////////// ACCOUNTING LOGIC //////////////////////////////////////////////////////////////*/ /** * @dev Returns the total amount of assets managed by the vault. * @return The total amount of assets. */ function totalAssets() external view returns (uint256); /** * @dev Calculates the amount of shares that would be minted for a given amount of assets. * @param assets The amount of assets to deposit. * @return shares The amount of shares that would be minted. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @dev Calculates the amount of assets that would be withdrawn for a given amount of shares. * @param shares The amount of shares to burn. * @return assets The amount of assets that would be withdrawn. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @dev Calculates the maximum amount of assets that can be deposited for a specific receiver. * @param receiver The address of the receiver. * @return maxAssets The maximum amount of assets that can be deposited. */ function maxDeposit(address receiver) external view returns (uint256 maxAssets); /** * @dev Simulates the effects of a deposit at the current block, given current on-chain conditions. * @param assets The amount of assets to deposit. * @return shares The amount of shares that would be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @dev Calculates the maximum amount of shares that can be minted for a specific receiver. * @param receiver The address of the receiver. * @return maxShares The maximum amount of shares that can be minted. */ function maxMint(address receiver) external view returns (uint256 maxShares); /** * @dev Simulates the effects of a mint at the current block, given current on-chain conditions. * @param shares The amount of shares to mint. * @return assets The amount of assets that would be deposited. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @dev Calculates the maximum amount of assets that can be withdrawn by a specific owner. * @param owner The address of the owner. * @return maxAssets The maximum amount of assets that can be withdrawn. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @dev Simulates the effects of a withdrawal at the current block, given current on-chain conditions. * @param assets The amount of assets to withdraw. * @return shares The amount of shares that would be burned. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @dev Calculates the maximum amount of shares that can be redeemed by a specific owner. * @param owner The address of the owner. * @return maxShares The maximum amount of shares that can be redeemed. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @dev Simulates the effects of a redemption at the current block, given current on-chain conditions. * @param shares The amount of shares to redeem. * @return assets The amount of assets that would be withdrawn. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; interface IEscrowVault { /** * @notice Deposit tokens on behalf of another account * @param account The address of the account * @param token The address of the token * @param amount The amount to increase the balance */ function deposit(address account, address token, uint256 amount) external; function withdraw(address token, uint256 amount) external ; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //records the unpause timestamp s interface IHasProtocolPausingManager { function getProtocolPausingManager() external view returns (address); // function isPauser(address _address) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; interface ILenderCommitmentGroup_V2 { struct CommitmentGroupConfig { address principalTokenAddress; address collateralTokenAddress; uint256 marketId; uint32 maxLoanDuration; uint16 interestRateLowerBound; uint16 interestRateUpperBound; uint16 liquidityThresholdPercent; uint16 collateralRatio; } function initialize( CommitmentGroupConfig calldata _commitmentGroupConfig, IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes ) external ; function liquidateDefaultedLoanWithIncentive( uint256 _bidId, int256 _tokenAmountDifference ) external ; function getTokenDifferenceFromLiquidations() external view returns (int256); }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; abstract contract ILenderManager is IERC721Upgradeable { /** * @notice Registers a new active lender for a loan, minting the nft. * @param _bidId The id for the loan to set. * @param _newLender The address of the new active lender. */ function registerLoan(uint256 _bidId, address _newLender) external virtual; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; //tellerv2 should support this interface ILoanRepaymentCallbacks { function setRepaymentListenerForBid(uint256 _bidId, address _listener) external; function getRepaymentListenerForBid(uint256 _bidId) external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; interface ILoanRepaymentListener { function repayLoanCallback( uint256 bidId, address repayer, uint256 principalAmount, uint256 interestAmount ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../EAS/TellerAS.sol"; import { PaymentType, PaymentCycleType } from "../libraries/V2Calculations.sol"; interface IMarketRegistry { function initialize(TellerAS tellerAs) external; function isVerifiedLender(uint256 _marketId, address _lender) external view returns (bool, bytes32); function isMarketOpen(uint256 _marketId) external view returns (bool); function isMarketClosed(uint256 _marketId) external view returns (bool); function isVerifiedBorrower(uint256 _marketId, address _borrower) external view returns (bool, bytes32); function getMarketOwner(uint256 _marketId) external view returns (address); function getMarketFeeRecipient(uint256 _marketId) external view returns (address); function getMarketURI(uint256 _marketId) external view returns (string memory); function getPaymentCycle(uint256 _marketId) external view returns (uint32, PaymentCycleType); function getPaymentDefaultDuration(uint256 _marketId) external view returns (uint32); function getBidExpirationTime(uint256 _marketId) external view returns (uint32); function getMarketplaceFee(uint256 _marketId) external view returns (uint16); function getPaymentType(uint256 _marketId) external view returns (PaymentType); function createMarket( address _initialOwner, uint32 _paymentCycleDuration, uint32 _paymentDefaultDuration, uint32 _bidExpirationTime, uint16 _feePercent, bool _requireLenderAttestation, bool _requireBorrowerAttestation, PaymentType _paymentType, PaymentCycleType _paymentCycleType, string calldata _uri ) external returns (uint256 marketId_); function createMarket( address _initialOwner, uint32 _paymentCycleDuration, uint32 _paymentDefaultDuration, uint32 _bidExpirationTime, uint16 _feePercent, bool _requireLenderAttestation, bool _requireBorrowerAttestation, string calldata _uri ) external returns (uint256 marketId_); function closeMarket(uint256 _marketId) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //records the unpause timestamp s interface IPausableTimestamp { function getLastUnpausedAt() external view returns (uint256) ; // function setLastUnpausedAt() internal; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IProtocolFee { function protocolFee() external view returns (uint16); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //records the unpause timestamp s interface IProtocolPausingManager { function isPauser(address _address) external view returns (bool); function protocolPaused() external view returns (bool); function liquidationsPaused() external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; enum RepMark { Good, Delinquent, Default } interface IReputationManager { function initialize(address protocolAddress) external; function getDelinquentLoanIds(address _account) external returns (uint256[] memory); function getDefaultedLoanIds(address _account) external returns (uint256[] memory); function getCurrentDelinquentLoanIds(address _account) external returns (uint256[] memory); function getCurrentDefaultLoanIds(address _account) external returns (uint256[] memory); function updateAccountReputation(address _account) external; function updateAccountReputation(address _account, uint256 _bidId) external returns (RepMark); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; enum CommitmentCollateralType { NONE, // no collateral required ERC20, ERC721, ERC1155, ERC721_ANY_ID, ERC1155_ANY_ID, ERC721_MERKLE_PROOF, ERC1155_MERKLE_PROOF } interface ISmartCommitment { function getPrincipalTokenAddress() external view returns (address); function getMarketId() external view returns (uint256); function getCollateralTokenAddress() external view returns (address); function getCollateralTokenType() external view returns (CommitmentCollateralType); // function getCollateralTokenId() external view returns (uint256); function getMinInterestRate(uint256 _delta) external view returns (uint16); function getMaxLoanDuration() external view returns (uint32); function getPrincipalAmountAvailableToBorrow() external view returns (uint256); function acceptFundsForAcceptBid( address _borrower, uint256 _bidId, uint256 _principalAmount, uint256 _collateralAmount, address _collateralTokenAddress, uint256 _collateralTokenId, uint32 _loanDuration, uint16 _interestRate ) external; }
pragma solidity >=0.8.0 <0.9.0; interface ISmartCommitmentForwarder { function acceptSmartCommitmentWithRecipient( address _smartCommitmentAddress, uint256 _principalAmount, uint256 _collateralAmount, uint256 _collateralTokenId, address _collateralTokenAddress, address _recipient, uint16 _interestRate, uint32 _loanDuration ) external returns (uint256 bidId) ; function setLiquidationProtocolFeePercent(uint256 _percent) external; function getLiquidationProtocolFeePercent() external view returns (uint256) ; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { Payment, BidState } from "../TellerV2Storage.sol"; import { Collateral } from "./escrow/ICollateralEscrowV1.sol"; interface ITellerV2 { /** * @notice Function for a borrower to create a bid for a loan. * @param _lendingToken The lending token asset requested to be borrowed. * @param _marketplaceId The unique id of the marketplace for the bid. * @param _principal The principal amount of the loan bid. * @param _duration The recurrent length of time before which a payment is due. * @param _APR The proposed interest rate for the loan bid. * @param _metadataURI The URI for additional borrower loan information as part of loan bid. * @param _receiver The address where the loan amount will be sent to. */ function submitBid( address _lendingToken, uint256 _marketplaceId, uint256 _principal, uint32 _duration, uint16 _APR, string calldata _metadataURI, address _receiver ) external returns (uint256 bidId_); /** * @notice Function for a borrower to create a bid for a loan with Collateral. * @param _lendingToken The lending token asset requested to be borrowed. * @param _marketplaceId The unique id of the marketplace for the bid. * @param _principal The principal amount of the loan bid. * @param _duration The recurrent length of time before which a payment is due. * @param _APR The proposed interest rate for the loan bid. * @param _metadataURI The URI for additional borrower loan information as part of loan bid. * @param _receiver The address where the loan amount will be sent to. * @param _collateralInfo Additional information about the collateral asset. */ function submitBid( address _lendingToken, uint256 _marketplaceId, uint256 _principal, uint32 _duration, uint16 _APR, string calldata _metadataURI, address _receiver, Collateral[] calldata _collateralInfo ) external returns (uint256 bidId_); /** * @notice Function for a lender to accept a proposed loan bid. * @param _bidId The id of the loan bid to accept. */ function lenderAcceptBid(uint256 _bidId) external returns ( uint256 amountToProtocol, uint256 amountToMarketplace, uint256 amountToBorrower ); /** * @notice Function for users to make the minimum amount due for an active loan. * @param _bidId The id of the loan to make the payment towards. */ function repayLoanMinimum(uint256 _bidId) external; /** * @notice Function for users to repay an active loan in full. * @param _bidId The id of the loan to make the payment towards. */ function repayLoanFull(uint256 _bidId) external; /** * @notice Function for users to make a payment towards an active loan. * @param _bidId The id of the loan to make the payment towards. * @param _amount The amount of the payment. */ function repayLoan(uint256 _bidId, uint256 _amount) external; /** * @notice Checks to see if a borrower is delinquent. * @param _bidId The id of the loan bid to check for. */ function isLoanDefaulted(uint256 _bidId) external view returns (bool); /** * @notice Checks to see if a loan was delinquent for longer than liquidation delay. * @param _bidId The id of the loan bid to check for. */ function isLoanLiquidateable(uint256 _bidId) external view returns (bool); /** * @notice Checks to see if a borrower is delinquent. * @param _bidId The id of the loan bid to check for. */ function isPaymentLate(uint256 _bidId) external view returns (bool); function getBidState(uint256 _bidId) external view returns (BidState); function getBorrowerActiveLoanIds(address _borrower) external view returns (uint256[] memory); /** * @notice Returns the borrower address for a given bid. * @param _bidId The id of the bid/loan to get the borrower for. * @return borrower_ The address of the borrower associated with the bid. */ function getLoanBorrower(uint256 _bidId) external view returns (address borrower_); /** * @notice Returns the lender address for a given bid. * @param _bidId The id of the bid/loan to get the lender for. * @return lender_ The address of the lender associated with the bid. */ function getLoanLender(uint256 _bidId) external view returns (address lender_); function getLoanLendingToken(uint256 _bidId) external view returns (address token_); function getLoanMarketId(uint256 _bidId) external view returns (uint256); function getLoanSummary(uint256 _bidId) external view returns ( address borrower, address lender, uint256 marketId, address principalTokenAddress, uint256 principalAmount, uint32 acceptedTimestamp, uint32 lastRepaidTimestamp, BidState bidState ); function calculateAmountOwed(uint256 _bidId, uint256 _timestamp) external view returns (Payment memory owed); function calculateAmountDue(uint256 _bidId, uint256 _timestamp) external view returns (Payment memory due); function lenderCloseLoan(uint256 _bidId) external; function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient) external; function liquidateLoanFull(uint256 _bidId) external; function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient) external; function getLoanDefaultTimestamp(uint256 _bidId) external view returns (uint256); function getEscrowVault() external view returns(address); function getProtocolFeeRecipient () external view returns(address); // function isPauser(address _account) external view returns(bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITellerV2Context { function setTrustedMarketForwarder(uint256 _marketId, address _forwarder) external; function approveMarketForwarder(uint256 _marketId, address _forwarder) external; }
// SPDX-Licence-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; interface IUniswapPricingLibrary { struct PoolRouteConfig { address pool; bool zeroForOne; uint32 twapInterval; uint256 token0Decimals; uint256 token1Decimals; } function getUniswapPriceRatioForPoolRoutes( PoolRouteConfig[] memory poolRoutes ) external view returns (uint256 priceRatio); function getUniswapPriceRatioForPool( PoolRouteConfig memory poolRoute ) external view returns (uint256 priceRatio); }
// SPDX-Licence-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; interface IOracleProtectionManager { function isOracleApproved(address _msgSender) external returns (bool) ; function isOracleApprovedAllowEOA(address _msgSender) external returns (bool); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; }
// 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 IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext( uint16 observationCardinalityNext ) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns ( int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s ); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol( uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New ); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol( address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1 ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// 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. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; // import "../../../interfaces/ILenderCommitmentGroupSharesIntegrated.sol"; /* This ERC20 token keeps track of the last time it was transferred and provides that information This can help mitigate sandwich attacking and flash loan attacking if additional external logic is used for that purpose Ideally , deploy this as a beacon proxy that is upgradeable */ abstract contract LenderCommitmentGroupSharesIntegrated is Initializable, ERC20Upgradeable // ILenderCommitmentGroupSharesIntegrated { uint8 private constant DECIMALS = 18; mapping(address => uint256) private poolSharesLastTransferredAt; event SharesLastTransferredAt( address indexed recipient, uint256 transferredAt ); /* The two tokens MUST implement IERC20Metadata or else this will fail. */ function __Shares_init( address principalTokenAddress, address collateralTokenAddress ) internal onlyInitializing { string memory principalTokenSymbol = IERC20Metadata(principalTokenAddress).symbol(); string memory collateralTokenSymbol = IERC20Metadata(collateralTokenAddress).symbol(); // Create combined name and symbol string memory combinedName = string(abi.encodePacked( principalTokenSymbol, "-", collateralTokenSymbol, " shares" )); string memory combinedSymbol = string(abi.encodePacked( principalTokenSymbol, "-", collateralTokenSymbol )); // Initialize with the dynamic name and symbol __ERC20_init(combinedName, combinedSymbol); } function mintShares(address _recipient, uint256 _amount) internal { // only wrapper contract can call _mint(_recipient, _amount); //triggers _afterTokenTransfer if (_amount > 0) { _setPoolSharesLastTransferredAt(_recipient); } } function burnShares(address _burner, uint256 _amount ) internal { // only wrapper contract can call _burn(_burner, _amount); //triggers _afterTokenTransfer if (_amount > 0) { _setPoolSharesLastTransferredAt(_burner); } } function decimals() public view virtual override returns (uint8) { return DECIMALS; } // this occurs after mint, burn and transfer function _afterTokenTransfer( address from, address to, uint256 amount ) internal override { if (amount > 0) { _setPoolSharesLastTransferredAt(from); } } function _setPoolSharesLastTransferredAt( address from ) internal { poolSharesLastTransferredAt[from] = block.timestamp; emit SharesLastTransferredAt(from, block.timestamp); } /* Get the last timestamp pool shares have been transferred for this account */ function getSharesLastTransferredAt( address owner ) public view returns (uint256) { return poolSharesLastTransferredAt[owner]; } // Storage gap for future upgrades uint256[50] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // https://aa.usno.navy.mil/faq/JD_formula.html // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int _month = (80 * L) / 2447; int _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint year, uint month, uint day, uint hour, uint minute, uint second ) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns ( uint year, uint month, uint day, uint hour, uint minute, uint second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint year, uint month, uint day, uint hour, uint minute, uint second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate( timestamp / SECONDS_PER_DAY ); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate( timestamp / SECONDS_PER_DAY ); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate( timestamp / SECONDS_PER_DAY ); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate( timestamp / SECONDS_PER_DAY ); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth, ) = _daysToDate( fromTimestamp / SECONDS_PER_DAY ); (uint toYear, uint toMonth, ) = _daysToDate( toTimestamp / SECONDS_PER_DAY ); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Libraries import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import "./WadRayMath.sol"; /** * @dev Utility library for uint256 numbers * * @author [email protected] */ library NumbersLib { using WadRayMath for uint256; /** * @dev It represents 100% with 2 decimal places. */ uint16 internal constant PCT_100 = 10000; function percentFactor(uint256 decimals) internal pure returns (uint256) { return 100 * (10**decimals); } /** * @notice Returns a percentage value of a number. * @param self The number to get a percentage of. * @param percentage The percentage value to calculate with 2 decimal places (10000 = 100%). */ function percent(uint256 self, uint16 percentage) internal pure returns (uint256) { return percent(self, percentage, 2); } /** * @notice Returns a percentage value of a number. * @param self The number to get a percentage of. * @param percentage The percentage value to calculate with. * @param decimals The number of decimals the percentage value is in. */ function percent(uint256 self, uint256 percentage, uint256 decimals) internal pure returns (uint256) { return (self * percentage) / percentFactor(decimals); } /** * @notice it returns the absolute number of a specified parameter * @param self the number to be returned in it's absolute * @return the absolute number */ function abs(int256 self) internal pure returns (uint256) { return self >= 0 ? uint256(self) : uint256(-1 * self); } /** * @notice Returns a ratio percentage of {num1} to {num2}. * @dev Returned value is type uint16. * @param num1 The number used to get the ratio for. * @param num2 The number used to get the ratio from. * @return Ratio percentage with 2 decimal places (10000 = 100%). */ function ratioOf(uint256 num1, uint256 num2) internal pure returns (uint16) { return SafeCast.toUint16(ratioOf(num1, num2, 2)); } /** * @notice Returns a ratio percentage of {num1} to {num2}. * @param num1 The number used to get the ratio for. * @param num2 The number used to get the ratio from. * @param decimals The number of decimals the percentage value is returned in. * @return Ratio percentage value. */ function ratioOf(uint256 num1, uint256 num2, uint256 decimals) internal pure returns (uint256) { if (num2 == 0) return 0; return (num1 * percentFactor(decimals)) / num2; } /** * @notice Calculates the payment amount for a cycle duration. * The formula is calculated based on the standard Estimated Monthly Installment (https://en.wikipedia.org/wiki/Equated_monthly_installment) * EMI = [P x R x (1+R)^N]/[(1+R)^N-1] * @param principal The starting amount that is owed on the loan. * @param loanDuration The length of the loan. * @param cycleDuration The length of the loan's payment cycle. * @param apr The annual percentage rate of the loan. */ function pmt( uint256 principal, uint32 loanDuration, uint32 cycleDuration, uint16 apr, uint256 daysInYear ) internal pure returns (uint256) { require( loanDuration >= cycleDuration, "PMT: cycle duration < loan duration" ); if (apr == 0) return Math.mulDiv( principal, cycleDuration, loanDuration, Math.Rounding.Up ); // Number of payment cycles for the duration of the loan uint256 n = Math.ceilDiv(loanDuration, cycleDuration); uint256 one = WadRayMath.wad(); uint256 r = WadRayMath.pctToWad(apr).wadMul(cycleDuration).wadDiv( daysInYear ); uint256 exp = (one + r).wadPow(n); uint256 numerator = principal.wadMul(r).wadMul(exp); uint256 denominator = exp - one; return numerator.wadDiv(denominator); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. // uint256 twos = -denominator & denominator; uint256 twos = (~denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(uint24(MAX_TICK)), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require( sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R" ); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24( (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128 ); int24 tickHi = int24( (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128 ); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; // Libraries import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "../interfaces/uniswap/IUniswapV3Pool.sol"; import "../libraries/uniswap/TickMath.sol"; import "../libraries/uniswap/FixedPoint96.sol"; import "../libraries/uniswap/FullMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /* Only do decimal expansion if it is an ERC20 not anything else !! */ library UniswapPricingLibraryV2 { uint256 constant STANDARD_EXPANSION_FACTOR = 1e18; function getUniswapPriceRatioForPoolRoutes( IUniswapPricingLibrary.PoolRouteConfig[] memory poolRoutes ) public view returns (uint256 priceRatio) { require(poolRoutes.length <= 2, "invalid pool routes length"); if (poolRoutes.length == 2) { uint256 pool0PriceRatio = getUniswapPriceRatioForPool( poolRoutes[0] ); uint256 pool1PriceRatio = getUniswapPriceRatioForPool( poolRoutes[1] ); return FullMath.mulDiv( pool0PriceRatio, pool1PriceRatio, STANDARD_EXPANSION_FACTOR ); } else if (poolRoutes.length == 1) { return getUniswapPriceRatioForPool(poolRoutes[0]); } //else return 0 } /* The resultant product is expanded by STANDARD_EXPANSION_FACTOR one time */ function getUniswapPriceRatioForPool( IUniswapPricingLibrary.PoolRouteConfig memory _poolRouteConfig ) public view returns (uint256 priceRatio) { // this is expanded by 2**96 or 1e28 uint160 sqrtPriceX96 = getSqrtTwapX96( _poolRouteConfig.pool, _poolRouteConfig.twapInterval ); bool invert = ! _poolRouteConfig.zeroForOne; //this output will be expanded by 1e18 return getQuoteFromSqrtRatioX96( sqrtPriceX96 , uint128( STANDARD_EXPANSION_FACTOR ), invert) ; } /** * @dev Calculates the amount of quote token received for a given amount of base token * based on the square root of the price ratio (sqrtRatioX96). Taken directly from uniswap oracle lib * * @param sqrtRatioX96 The square root of the price ratio(in terms of token1/token0) between two tokens, encoded as a Q64.96 value. * @param baseAmount The amount of the base token for which the quote is to be calculated. Specify 1e18 for a price(quoteAmount) with 18 decimals of precision. * @param inverse Specifies the direction of the price quote. If true then baseAmount must be the amount of token1, if false then baseAmount must be the amount for token0 * * @return quoteAmount The calculated amount of the quote token for the specified baseAmount */ function getQuoteFromSqrtRatioX96( uint160 sqrtRatioX96, uint128 baseAmount, bool inverse ) internal pure returns (uint256 quoteAmount) { // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = !inverse ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv( sqrtRatioX96, sqrtRatioX96, 1 << 64 ); quoteAmount = !inverse ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval) internal view returns (uint160 sqrtPriceX96) { if (twapInterval == 0) { // return the current price if twapInterval == 0 (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); } else { uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = twapInterval + 1; // from (before) secondsAgos[1] = 1; // one block prior (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool) .observe(secondsAgos); // tick(imprecise as it's an integer) to price sqrtPriceX96 = TickMath.getSqrtRatioAtTick( int24( (tickCumulatives[1] - tickCumulatives[0]) / int32(twapInterval) ) ); } } function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96) internal pure returns (uint256 priceX96) { return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); } }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT // Libraries import "./NumbersLib.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import { Bid } from "../TellerV2Storage.sol"; import { BokkyPooBahsDateTimeLibrary as BPBDTL } from "./DateTimeLib.sol"; enum PaymentType { EMI, Bullet } enum PaymentCycleType { Seconds, Monthly } library V2Calculations { using NumbersLib for uint256; /** * @notice Returns the timestamp of the last payment made for a loan. * @param _bid The loan bid struct to get the timestamp for. */ function lastRepaidTimestamp(Bid storage _bid) internal view returns (uint32) { return _bid.loanDetails.lastRepaidTimestamp == 0 ? _bid.loanDetails.acceptedTimestamp : _bid.loanDetails.lastRepaidTimestamp; } /** * @notice Calculates the amount owed for a loan. * @param _bid The loan bid struct to get the owed amount for. * @param _timestamp The timestamp at which to get the owed amount at. * @param _paymentCycleType The payment cycle type of the loan (Seconds or Monthly). */ function calculateAmountOwed( Bid storage _bid, uint256 _timestamp, PaymentCycleType _paymentCycleType, uint32 _paymentCycleDuration ) public view returns ( uint256 owedPrincipal_, uint256 duePrincipal_, uint256 interest_ ) { // Total principal left to pay return calculateAmountOwed( _bid, lastRepaidTimestamp(_bid), _timestamp, _paymentCycleType, _paymentCycleDuration ); } function calculateAmountOwed( Bid storage _bid, uint256 _lastRepaidTimestamp, uint256 _timestamp, PaymentCycleType _paymentCycleType, uint32 _paymentCycleDuration ) public view returns ( uint256 owedPrincipal_, uint256 duePrincipal_, uint256 interest_ ) { owedPrincipal_ = _bid.loanDetails.principal - _bid.loanDetails.totalRepaid.principal; uint256 owedTime = _timestamp - uint256(_lastRepaidTimestamp); { uint256 daysInYear = _paymentCycleType == PaymentCycleType.Monthly ? 360 days : 365 days; uint256 interestOwedInAYear = owedPrincipal_.percent(_bid.terms.APR, 2); interest_ = (interestOwedInAYear * owedTime) / daysInYear; } bool isLastPaymentCycle; { uint256 lastPaymentCycleDuration = _bid.loanDetails.loanDuration % _paymentCycleDuration; if (lastPaymentCycleDuration == 0) { lastPaymentCycleDuration = _paymentCycleDuration; } uint256 endDate = uint256(_bid.loanDetails.acceptedTimestamp) + uint256(_bid.loanDetails.loanDuration); uint256 lastPaymentCycleStart = endDate - uint256(lastPaymentCycleDuration); isLastPaymentCycle = uint256(_timestamp) > lastPaymentCycleStart || owedPrincipal_ + interest_ <= _bid.terms.paymentCycleAmount; } if (_bid.paymentType == PaymentType.Bullet) { if (isLastPaymentCycle) { duePrincipal_ = owedPrincipal_; } } else { // Default to PaymentType.EMI // Max payable amount in a cycle // NOTE: the last cycle could have less than the calculated payment amount //the amount owed for the cycle should never exceed the current payment cycle amount so we use min here uint256 owedAmountForCycle = Math.min( ((_bid.terms.paymentCycleAmount * owedTime) ) / _paymentCycleDuration , _bid.terms.paymentCycleAmount+interest_ ) ; uint256 owedAmount = isLastPaymentCycle ? owedPrincipal_ + interest_ : owedAmountForCycle ; duePrincipal_ = Math.min(owedAmount - interest_, owedPrincipal_); } } /** * @notice Calculates the amount owed for a loan for the next payment cycle. * @param _type The payment type of the loan. * @param _cycleType The cycle type set for the loan. (Seconds or Monthly) * @param _principal The starting amount that is owed on the loan. * @param _duration The length of the loan. * @param _paymentCycle The length of the loan's payment cycle. * @param _apr The annual percentage rate of the loan. */ function calculatePaymentCycleAmount( PaymentType _type, PaymentCycleType _cycleType, uint256 _principal, uint32 _duration, uint32 _paymentCycle, uint16 _apr ) public view returns (uint256) { uint256 daysInYear = _cycleType == PaymentCycleType.Monthly ? 360 days : 365 days; if (_type == PaymentType.Bullet) { return _principal.percent(_apr).percent( uint256(_paymentCycle).ratioOf(daysInYear, 10), 10 ); } // Default to PaymentType.EMI return NumbersLib.pmt( _principal, _duration, _paymentCycle, _apr, daysInYear ); } function calculateNextDueDate( uint32 _acceptedTimestamp, uint32 _paymentCycle, uint32 _loanDuration, uint32 _lastRepaidTimestamp, PaymentCycleType _bidPaymentCycleType ) public view returns (uint32 dueDate_) { // Calculate due date if payment cycle is set to monthly if (_bidPaymentCycleType == PaymentCycleType.Monthly) { // Calculate the cycle number the last repayment was made uint256 lastPaymentCycle = BPBDTL.diffMonths( _acceptedTimestamp, _lastRepaidTimestamp ); if ( BPBDTL.getDay(_lastRepaidTimestamp) > BPBDTL.getDay(_acceptedTimestamp) ) { lastPaymentCycle += 2; } else { lastPaymentCycle += 1; } dueDate_ = uint32( BPBDTL.addMonths(_acceptedTimestamp, lastPaymentCycle) ); } else if (_bidPaymentCycleType == PaymentCycleType.Seconds) { // Start with the original due date being 1 payment cycle since bid was accepted dueDate_ = _acceptedTimestamp + _paymentCycle; // Calculate the cycle number the last repayment was made uint32 delta = _lastRepaidTimestamp - _acceptedTimestamp; if (delta > 0) { uint32 repaymentCycle = uint32( Math.ceilDiv(delta, _paymentCycle) ); dueDate_ += (repaymentCycle * _paymentCycle); } } uint32 endOfLoan = _acceptedTimestamp + _loanDuration; //if we are in the last payment cycle, the next due date is the end of loan duration if (dueDate_ > endOfLoan) { dueDate_ = endOfLoan; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title WadRayMath library * @author Multiplier Finance * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) */ library WadRayMath { using SafeMath for uint256; uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; uint256 internal constant PCT_WAD_RATIO = 1e14; uint256 internal constant PCT_RAY_RATIO = 1e23; function ray() internal pure returns (uint256) { return RAY; } function wad() internal pure returns (uint256) { return WAD; } function halfRay() internal pure returns (uint256) { return halfRAY; } function halfWad() internal pure returns (uint256) { return halfWAD; } function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfWAD.add(a.mul(b)).div(WAD); } function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(WAD)).div(b); } function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfRAY.add(a.mul(b)).div(RAY); } function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(RAY)).div(b); } function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; return halfRatio.add(a).div(WAD_RAY_RATIO); } function rayToPct(uint256 a) internal pure returns (uint16) { uint256 halfRatio = PCT_RAY_RATIO / 2; uint256 val = halfRatio.add(a).div(PCT_RAY_RATIO); return SafeCast.toUint16(val); } function wadToPct(uint256 a) internal pure returns (uint16) { uint256 halfRatio = PCT_WAD_RATIO / 2; uint256 val = halfRatio.add(a).div(PCT_WAD_RATIO); return SafeCast.toUint16(val); } function wadToRay(uint256 a) internal pure returns (uint256) { return a.mul(WAD_RAY_RATIO); } function pctToRay(uint16 a) internal pure returns (uint256) { return uint256(a).mul(RAY).div(1e4); } function pctToWad(uint16 a) internal pure returns (uint256) { return uint256(a).mul(WAD).div(1e4); } /** * @dev calculates base^duration. The code uses the ModExp precompile * @return z base^duration, in ray */ function rayPow(uint256 x, uint256 n) internal pure returns (uint256) { return _pow(x, n, RAY, rayMul); } function wadPow(uint256 x, uint256 n) internal pure returns (uint256) { return _pow(x, n, WAD, wadMul); } function _pow( uint256 x, uint256 n, uint256 p, function(uint256, uint256) internal pure returns (uint256) mul ) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : p; for (n /= 2; n != 0; n /= 2) { x = mul(x, x); if (n % 2 != 0) { z = mul(z, x); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IOracleProtectionManager} from "../interfaces/oracleprotection/IOracleProtectionManager.sol"; abstract contract OracleProtectedChild { address public immutable ORACLE_MANAGER; modifier onlyOracleApproved() { IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER); require( oracleManager .isOracleApproved(msg.sender ) , "Oracle: Not Approved"); _; } modifier onlyOracleApprovedAllowEOA() { IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER); require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , "Oracle: Not Approved"); _; } constructor(address oracleManager){ ORACLE_MANAGER = oracleManager; } }
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import { IMarketRegistry } from "./interfaces/IMarketRegistry.sol"; import "./interfaces/IEscrowVault.sol"; import "./interfaces/IReputationManager.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/ICollateralManager.sol"; import { PaymentType, PaymentCycleType } from "./libraries/V2Calculations.sol"; import "./interfaces/ILenderManager.sol"; enum BidState { NONEXISTENT, PENDING, CANCELLED, ACCEPTED, PAID, LIQUIDATED, CLOSED } /** * @notice Represents a total amount for a payment. * @param principal Amount that counts towards the principal. * @param interest Amount that counts toward interest. */ struct Payment { uint256 principal; uint256 interest; } /** * @notice Details about a loan request. * @param borrower Account address who is requesting a loan. * @param receiver Account address who will receive the loan amount. * @param lender Account address who accepted and funded the loan request. * @param marketplaceId ID of the marketplace the bid was submitted to. * @param metadataURI ID of off chain metadata to find additional information of the loan request. * @param loanDetails Struct of the specific loan details. * @param terms Struct of the loan request terms. * @param state Represents the current state of the loan. */ struct Bid { address borrower; address receiver; address lender; // if this is the LenderManager address, we use that .owner() as source of truth uint256 marketplaceId; bytes32 _metadataURI; // DEPRECATED LoanDetails loanDetails; Terms terms; BidState state; PaymentType paymentType; } /** * @notice Details about the loan. * @param lendingToken The token address for the loan. * @param principal The amount of tokens initially lent out. * @param totalRepaid Payment struct that represents the total principal and interest amount repaid. * @param timestamp Timestamp, in seconds, of when the bid was submitted by the borrower. * @param acceptedTimestamp Timestamp, in seconds, of when the bid was accepted by the lender. * @param lastRepaidTimestamp Timestamp, in seconds, of when the last payment was made * @param loanDuration The duration of the loan. */ struct LoanDetails { IERC20 lendingToken; uint256 principal; Payment totalRepaid; uint32 timestamp; uint32 acceptedTimestamp; uint32 lastRepaidTimestamp; uint32 loanDuration; } /** * @notice Information on the terms of a loan request * @param paymentCycleAmount Value of tokens expected to be repaid every payment cycle. * @param paymentCycle Duration, in seconds, of how often a payment must be made. * @param APR Annual percentage rating to be applied on repayments. (10000 == 100%) */ struct Terms { uint256 paymentCycleAmount; uint32 paymentCycle; uint16 APR; } abstract contract TellerV2Storage_G0 { /** Storage Variables */ // Current number of bids. uint256 public bidId; // Mapping of bidId to bid information. mapping(uint256 => Bid) public bids; // Mapping of borrowers to borrower requests. mapping(address => uint256[]) public borrowerBids; // Mapping of volume filled by lenders. mapping(address => uint256) public __lenderVolumeFilled; // DEPRECIATED // Volume filled by all lenders. uint256 public __totalVolumeFilled; // DEPRECIATED // List of allowed lending tokens EnumerableSet.AddressSet internal __lendingTokensSet; // DEPRECATED IMarketRegistry public marketRegistry; IReputationManager public reputationManager; // Mapping of borrowers to borrower requests. mapping(address => EnumerableSet.UintSet) internal _borrowerBidsActive; mapping(uint256 => uint32) public bidDefaultDuration; mapping(uint256 => uint32) public bidExpirationTime; // Mapping of volume filled by lenders. // Asset address => Lender address => Volume amount mapping(address => mapping(address => uint256)) public lenderVolumeFilled; // Volume filled by all lenders. // Asset address => Volume amount mapping(address => uint256) public totalVolumeFilled; uint256 public version; // Mapping of metadataURIs by bidIds. // Bid Id => metadataURI string mapping(uint256 => string) public uris; } abstract contract TellerV2Storage_G1 is TellerV2Storage_G0 { // market ID => trusted forwarder mapping(uint256 => address) internal _trustedMarketForwarders; // trusted forwarder => set of pre-approved senders mapping(address => EnumerableSet.AddressSet) internal _approvedForwarderSenders; } abstract contract TellerV2Storage_G2 is TellerV2Storage_G1 { address public lenderCommitmentForwarder; } abstract contract TellerV2Storage_G3 is TellerV2Storage_G2 { ICollateralManager public collateralManager; } abstract contract TellerV2Storage_G4 is TellerV2Storage_G3 { // Address of the lender manager contract ILenderManager public lenderManager; // BidId to payment cycle type (custom or monthly) mapping(uint256 => PaymentCycleType) public bidPaymentCycleType; } abstract contract TellerV2Storage_G5 is TellerV2Storage_G4 { // Address of the lender manager contract IEscrowVault public escrowVault; } abstract contract TellerV2Storage_G6 is TellerV2Storage_G5 { mapping(uint256 => address) public repaymentListenerForBid; } abstract contract TellerV2Storage_G7 is TellerV2Storage_G6 { mapping(address => bool) private __pauserRoleBearer; bool private __liquidationsPaused; } abstract contract TellerV2Storage_G8 is TellerV2Storage_G7 { address protocolFeeRecipient; } abstract contract TellerV2Storage is TellerV2Storage_G8 {}
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT // A representation of an empty/uninitialized UUID. bytes32 constant EMPTY_UUID = 0;
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": { "contracts/libraries/UniswapPricingLibraryV2.sol": { "UniswapPricingLibraryV2": "0xfddcec68cfa40c38faf05f918484fc416a221bff" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_tellerV2","type":"address"},{"internalType":"address","name":"_smartCommitmentForwarder","type":"address"},{"internalType":"address","name":"_uniswapV3Factory","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":"STANDARD_EXPANSION_FACTOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":[],"name":"UNISWAP_V3_FACTORY","outputs":[{"internalType":"address","name":"","type":"address"}],"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":[{"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":"poolOracleRoutes","type":"tuple[]"}],"name":"getPrincipalForCollateralForPoolRoutes","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_V2.CommitmentGroupConfig","name":"_commitmentGroupConfig","type":"tuple"},{"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":"_poolOracleRoutes","type":"tuple[]"}],"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":"","type":"uint256"}],"name":"poolOracleRoutes","outputs":[{"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"}],"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":"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":"_maxPrincipalPerCollateralAmount","type":"uint256"}],"name":"setMaxPrincipalPerCollateralAmount","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"}]
Contract Creation Code
6101c0604052670de0b6b3a764000060a052600360c0526c0100000000000000000000000060e0526ec097ce7bc90715b34b9f10000000006101005261012c61018052620151806101a0523480156200005757600080fd5b5060405162006258380380620062588339810160408190526200007a91620000c0565b6001600160a01b039182166080819052928216610120526101409290925216610160526200010a565b80516001600160a01b0381168114620000bb57600080fd5b919050565b600080600060608486031215620000d657600080fd5b620000e184620000a3565b9250620000f160208501620000a3565b91506200010160408501620000a3565b90509250925092565b60805160a05160c05160e05161010051610120516101405161016051610180516101a051615fac620002ac60003960008181610c1f0152610f23015260008181610714015261123401526000610bda0152600081816106e40152818161126d01528181611ab50152818161201701528181612321015281816126170152818161266f01528181612be3015281816131d50152818161348b015281816137e30152613c5a01526000818161078301528181610c6701528181610e5c01528181610faa01528181611295015281816116e9015281816118da01528181611ed30152818161223d015281816123dd01528181612555015281816128c001528181612a2201528181613090015281816138a801528181614719015281816147c6015281816149990152614a2c0152600081816108c901528181611ea0015281816129b0015281816129db01528181613e480152613fa8015260006109ab0152600061096901526000818161069a0152614407015260008181610b1e01528181611b930152818161216b01528181612cc1015281816132b301526135690152615fac6000f3fe608060405234801561001057600080fd5b506004361061050f5760003560e01c80637701a84c116102a4578063ba08765211610172578063ded7abc6116100d9578063f57781fe11610092578063f57781fe14610bc2578063f73e5aab14610bd5578063f84d68fd14610bfc578063f87bc1c814610c10578063fa4c1d5a14610c1a578063fa83a97614610c4157600080fd5b8063ded7abc614610b81578063e07baba614610b94578063ef8b30f714610abe578063f2fde38b14610b9e578063f319986114610bb1578063f540744414610bba57600080fd5b8063ce96cb771161012b578063ce96cb7714610b06578063d24bc1a414610b19578063d2c76fd814610b40578063d905777e14610b48578063dbc162de14610b5b578063dd62ed3e14610b6e57600080fd5b8063ba08765214610aab578063c63d75b614610682578063c6e6f59214610abe578063c84f95dd14610ad1578063ca0c1bb014610ae0578063cc9ce35a14610af357600080fd5b8063a457c2d711610216578063ac6787bb116101cf578063ac6787bb14610a3d578063b2016bd414610a53578063b3d7f6b914610a66578063b460af9414610a79578063b4cebd5714610a8c578063b4eae1cb14610a9657600080fd5b8063a457c2d7146109cd578063a4be77ee146109e0578063a5c2f9c4146109f9578063a7fc093d14610a0c578063a9059cbb14610a22578063aa09d5b714610a3557600080fd5b80638da5cb5b116102685780638da5cb5b14610940578063913ff9a91461095157806391bf279b1461096457806394bf804d1461098b57806395d89b411461099e578063a11ea0ed146109a657600080fd5b80637701a84c146108fe5780637faf15621461091157806380bde5ac14610919578063846be29e1461092c5780638b1908601461093657600080fd5b8063475d9694116103e1578063667a65d911610353578063715018a61161030c578063715018a61461088357806371f3ec561461088b578063739dd659146108b457806373aa6b57146108bc578063764f5963146108c457806376f28daf146108eb57600080fd5b8063667a65d9146107f5578063672b0774146108085780636d483fe61461082c5780636e553f651461083d5780636f7833131461085057806370a082311461085a57600080fd5b8063568ef470116103a5578063568ef470146107365780635932f4ff1461073e5780635bb2c822146107665780635c975abb146107705780636051f2101461077e5780636298deab146107a557600080fd5b8063475d9694146106d757806349c3d6e6146106df5780634b1dd53b146107065780634cdad5061461054e578063562d75381461070f57600080fd5b80631d42a60e11610485578063395093511161043e578063395093511461064d5780633f9be66614610660578063402d267d14610682578063424ddc4a14610695578063439d766d146106bc5780634523d6f7146106c457600080fd5b80631d42a60e146105d257806323b872dd146105e5578063280e32fb146105f8578063313ce5671461061d578063318213081461062c57806338d52e0f146105f857600080fd5b8063095ea7b3116104d7578063095ea7b3146105745780630a28a477146105975780631446cc24146105aa578063167c6314146105b457806318160ddd146105bc5780631d24a6e4146105c457600080fd5b806301e1d11414610514578063068cc5141461052f57806306fdde031461053957806307a2d13a1461054e57806308a6355a14610561575b600080fd5b61051c610c54565b6040519081526020015b60405180910390f35b610537610c63565b005b610541610daf565b60405161052691906151c7565b61051c61055c3660046151fa565b610e41565b61053761056f3660046151fa565b610e5a565b610587610582366004615228565b610f7b565b6040519015158152602001610526565b61051c6105a53660046151fa565b610f93565b61051c6101005481565b610537610fa6565b60995461051c565b610109546105879060ff1681565b6105376105e0366004615254565b6110e1565b6105876105f33660046152e4565b611651565b60fc546001600160a01b03165b6040516001600160a01b039091168152602001610526565b60405160128152602001610526565b61051c61063a3660046151fa565b6101076020526000908152604090205481565b61058761065b366004615228565b611677565b6101055461066f9061ffff1681565b60405161ffff9091168152602001610526565b61051c610690366004615325565b611699565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b6105376116e5565b61051c6106d23660046151fa565b611822565b6105376118d6565b6106057f000000000000000000000000000000000000000000000000000000000000000081565b6101085461051c565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b60fe5461051c565b61010554640100000000900463ffffffff165b60405163ffffffff9091168152602001610526565b61051c6101035481565b61010e546105879060ff1681565b6106057f000000000000000000000000000000000000000000000000000000000000000081565b6107b86107b33660046151fa565b611a12565b604080516001600160a01b039096168652931515602086015263ffffffff909216928401929092526060830191909152608082015260a001610526565b61066f6108033660046151fa565b611a6a565b6105876108163660046151fa565b6101066020526000908152604090205460ff1681565b60fd546001600160a01b0316610605565b61051c61084b366004615342565b611ab1565b61051c6101045481565b61051c610868366004615325565b6001600160a01b031660009081526097602052604090205490565b610537611e7d565b61051c610899366004615325565b6001600160a01b0316600090815260c9602052604090205490565b61051c611e91565b610537611ecf565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b6105376108f9366004615372565b612015565b61053761090c3660046153b8565b61260c565b61051c612994565b6105376109273660046151fa565b612a09565b61051c61010c5481565b61051c61010a5481565b6033546001600160a01b0316610605565b61053761095f366004615439565b612a17565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b61051c610999366004615342565b612bdf565b610541612f96565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b6105876109db366004615228565b612fa5565b6101055461075190640100000000900463ffffffff1681565b61066f610a073660046151fa565b61302b565b6101055461066f90600160501b900461ffff1681565b610587610a30366004615228565b61307e565b61053761308c565b6101055461066f90600160401b900461ffff1681565b60fd54610605906001600160a01b031681565b61051c610a743660046151fa565b6131c3565b61051c610a87366004615476565b6131d1565b61051c6101015481565b6101055461066f9062010000900461ffff1681565b61051c610ab9366004615476565b613487565b61051c610acc3660046151fa565b613730565b600160405161052691906154ce565b61051c610aee366004615574565b61373e565b610537610b013660046151fa565b6137e1565b61051c610b14366004615325565b6139bf565b6106057f000000000000000000000000000000000000000000000000000000000000000081565b61051c613a76565b61051c610b56366004615325565b613ac4565b60fc54610605906001600160a01b031681565b61051c610b7c366004615677565b613bae565b61010e5461058790610100900460ff1681565b61051c61010d5481565b610537610bac366004615325565b613bd9565b61051c60ff5481565b61051c613c4f565b61051c610bd0366004615372565b613cda565b6106057f000000000000000000000000000000000000000000000000000000000000000081565b61010e546105879062010000900460ff1681565b61051c6101025481565b61051c7f000000000000000000000000000000000000000000000000000000000000000081565b61051c610c4f3660046151fa565b613d6c565b6000610c5e613d94565b905090565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce791906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015610d2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d5291906156c2565b610d775760405162461bcd60e51b8152600401610d6e906156df565b60405180910390fd5b61010e5460ff16610d9a5760405162461bcd60e51b8152600401610d6e906156fb565b610da44261010d55565b610dac613de8565b50565b6060609a8054610dbe90615716565b80601f0160208091040260200160405190810160405280929190818152602001828054610dea90615716565b8015610e375780601f10610e0c57610100808354040283529160200191610e37565b820191906000526020600020905b815481529060010190602001808311610e1a57829003601f168201915b5050505050905090565b6000610e5482610e4f611e91565b613e33565b92915050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610eb8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edc91906156a5565b6001600160a01b0316336001600160a01b031614610f215760405162461bcd60e51b81526020600482015260026024820152614f4f60f01b6044820152606401610d6e565b7f00000000000000000000000000000000000000000000000000000000000000008110610f755760405162461bcd60e51b815260206004820152600260248201526115d160f21b6044820152606401610d6e565b61010a55565b600033610f89818585613e6f565b5060019392505050565b6000610e5482610fa1612994565b613f93565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611006573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102a91906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015611071573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061109591906156c2565b6110b15760405162461bcd60e51b8152600401610d6e906156df565b61010e54610100900460ff166110d95760405162461bcd60e51b8152600401610d6e906156fb565b610dac613fcf565b600054610100900460ff16158080156111015750600054600160ff909116105b8061111b5750303b15801561111b575060005460ff166001145b61117e5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d6e565b6000805460ff1916600117905580156111a1576000805461ff0019166101001790555b6111a9614002565b6111ce6111b96020860186615325565b6111c96040870160208801615325565b614031565b6111db6020850185615325565b60fc80546001600160a01b0319166001600160a01b039290921691909117905561120b6040850160208601615325565b60fd80546001600160a01b0319166001600160a01b0392831617905560408581013560fe8190557f000000000000000000000000000000000000000000000000000000000000000061010a559051630ba4ccb560e21b815260048101919091527f0000000000000000000000000000000000000000000000000000000000000000821660248201527f000000000000000000000000000000000000000000000000000000000000000090911690632e9332d490604401600060405180830381600087803b1580156112db57600080fd5b505af11580156112ef573d6000803e3d6000fd5b50611304925050506080850160608601615751565b610105805463ffffffff929092166401000000000267ffffffff000000001990921691909117905561133c60a085016080860161576e565b610105805461ffff92909216600160401b0269ffff00000000000000001990921691909117905561137360c0850160a0860161576e565b610105805461ffff60501b1916600160501b61ffff9384168102919091179182905581048216600160401b90910490911611156113db5760405162461bcd60e51b8152600401610d6e9060208082526004908201526324a9262160e11b604082015260600190565b6113eb60e0850160c0860161576e565b610105805461ffff191661ffff92909216919091179055611413610100850160e0860161576e565b610105805461ffff928316620100000263ffff0000198216811790925561271091831692169190911711156114735760405162461bcd60e51b8152600401610d6e906020808252600490820152630494c54560e41b604082015260600190565b60005b828110156114d65761010b84848381811061149357611493615789565b83546001810185556000948552602090942060a0909102929092019260030290910190506114c1828261579f565b505080806114ce90615855565b915050611476565b5061010b546001118015906114ef575061010b54600210155b6115215760405162461bcd60e51b815260206004820152600360248201526214149360ea1b6044820152606401610d6e565b6115316040850160208601615325565b6001600160a01b03166115476020860186615325565b6001600160a01b03167f39a60e55b000e31daa0c5bae68cfc6256176f9ae4e9fa343e5224410a69c1ebb60408701356115866080890160608a01615751565b61159660a08a0160808b0161576e565b6115a660c08b0160a08c0161576e565b6115b660e08c0160c08d0161576e565b6115c76101008d0160e08e0161576e565b6040805196875263ffffffff95909516602087015261ffff938416868601529183166060860152821660808501521660a0830152519081900360c00190a3801561164b576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60003361165f85828561418a565b61166a8585856141fe565b60019150505b9392505050565b600033610f8981858561168a8383613bae565b6116949190615870565b613e6f565b61010e5460009060ff16156116b057506000919050565b6101095460ff161580156116cf57506033546001600160a01b03163314155b156116dc57506000919050565b50600019919050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611745573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176991906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa1580156117b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d491906156c2565b6117f05760405162461bcd60e51b8152600401610d6e906156df565b61010e5462010000900460ff161561181a5760405162461bcd60e51b8152600401610d6e906156fb565b610dac6143af565b60008073fddcec68cfa40c38faf05f918484fc416a221bff63caf0f03361010b6040518263ffffffff1660e01b815260040161185e9190615888565b602060405180830381865af415801561187b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061189f9190615911565b9050600061010c546000146118c0576118bb8261010c546143e9565b6118c2565b815b90506118ce84826143ff565b949350505050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611936573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061195a91906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa1580156119a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c591906156c2565b6119e15760405162461bcd60e51b8152600401610d6e906156df565b61010e54610100900460ff1615611a0a5760405162461bcd60e51b8152600401610d6e906156fb565b610dac61442e565b61010b8181548110611a2357600080fd5b60009182526020909120600390910201805460018201546002909201546001600160a01b0382169350600160a01b820460ff1692600160a81b90920463ffffffff16919085565b6000611a74613d94565b611a8057506000919050565b610e54611aa983611a8f614466565b611a999190615870565b612710611aa4613d94565b61448e565b6127106143e9565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b3591906156c2565b15611b525760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff1615611b765760405162461bcd60e51b8152600401610d6e906156fb565b611b7e61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015611be6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c0a91906156c2565b611c265760405162461bcd60e51b8152600401610d6e90615949565b60008411611c3357600080fd5b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611c7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca09190615911565b60fc54909150611cbb906001600160a01b0316333088614598565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611d04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d289190615911565b9050611d348683615870565b8114611d675760405162461bcd60e51b81526020600482015260026024820152612a2160f11b6044820152606401610d6e565b611d7386610e4f612994565b93508560ff6000828254611d879190615870565b90915550611d9790508585614603565b6101095460ff16611e29576033546001600160a01b03163314611de25760405162461bcd60e51b815260206004820152600360248201526246444d60e81b6044820152606401610d6e565b620f4240841015611e1a5760405162461bcd60e51b8152602060048201526002602482015261495360f01b6044820152606401610d6e565b610109805460ff191660011790555b60408051878152602081018690526001600160a01b0387169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d791015b60405180910390a3505050610e546001606555565b611e85614620565b611e8f600061467a565b565b6000611e9b612994565b611ec57f000000000000000000000000000000000000000000000000000000000000000080615977565b610c5e91906159ac565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f2f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f5391906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015611f9a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbe91906156c2565b611fda5760405162461bcd60e51b8152600401610d6e906156df565b61010e5462010000900460ff166120035760405162461bcd60e51b8152600401610d6e906156fb565b61200d4261010d55565b610dac6146cc565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612073573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061209791906156c2565b156120b45760405162461bcd60e51b8152600401610d6e9061592a565b61010e5462010000900460ff16156120de5760405162461bcd60e51b8152600401610d6e906156fb565b61010e5460ff16156121025760405162461bcd60e51b8152600401610d6e906156fb565b60008281526101066020526040902054829060ff16151560011461214e5760405162461bcd60e51b8152602060048201526003602482015262424e4160e81b6044820152606401610d6e565b61215661453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690639df10fe0906024016020604051808303816000875af11580156121be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e291906156c2565b6121fe5760405162461bcd60e51b8152600401610d6e90615949565b600061220985614700565b90506000806122178761479b565b604051634b67a05b60e11b8152600481018a905291935091506000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906396cf40b690602401602060405180830381865afa158015612284573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122a89190615911565b905060006122bd826122b8613c4f565b614843565b905060006122cb8683613cda565b9050808912156123035760405162461bcd60e51b815260206004820152600360248201526215105160ea1b6044820152606401610d6e565b60008113156124c057600061231782614852565b905060006123a9827f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f8cbc5d66040518163ffffffff1660e01b8152600401602060405180830381865afa15801561237d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123a19190615911565b61271061448e565b90506123d93330836123bb868c615870565b6123c591906159c0565b60fc546001600160a01b0316929190614598565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166372c8fc0e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612439573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061245d91906156a5565b9050811561247d5760fc5461247d906001600160a01b0316338385614598565b8761010260008282546124909190615870565b909155506124a0905082846159c0565b61010860008282546124b291906159d7565b909155506125399350505050565b60006124cb82614852565b9050858111156124d85750845b60006124e482886159c0565b905080156125045760fc54612504906001600160a01b0316333084614598565b8661010260008282546125179190615870565b925050819055508161010860008282546125319190615a18565b909155505050505b604051630da8959360e01b8152600481018b90523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690630da8959390604401600060405180830381600087803b1580156125a157600080fd5b505af11580156125b5573d6000803e3d6000fd5b505060408051888152602081018d90523393508d92507f274d762f568e6bddf149314ec29fac2cc57609d38374d13f92dad87efa588387910160405180910390a3505050505050506126076001606555565b505050565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461266d5760405162461bcd60e51b8152600401610d6e9060208082526004908201526327a9a1a360e11b604082015260600190565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126ef91906156c2565b1561270c5760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156127305760405162461bcd60e51b8152600401610d6e906156fb565b61010e54610100900460ff16156127595760405162461bcd60e51b8152600401610d6e906156fb565b60fd546001600160a01b0385811691161461279f5760405162461bcd60e51b8152600401610d6e90602080825260049082015263135350d560e21b604082015260600190565b6127a88661302b565b61ffff168161ffff1610156127e55760405162461bcd60e51b815260206004820152600360248201526224a4a960e91b6044820152606401610d6e565b6101055463ffffffff640100000000909104811690831611156128305760405162461bcd60e51b815260206004820152600360248201526213135160ea1b6044820152606401610d6e565b85612839613a76565b101561286d5760405162461bcd60e51b815260206004820152600360248201526204c4d560ec1b6044820152606401610d6e565b600061287887613d6c565b9050808610156128ae5760405162461bcd60e51b81526020600482015260016024820152604360f81b6044820152606401610d6e565b60fc546128e5906001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000008961486e565b6128ee88614983565b8661010160008282546129019190615870565b9091555050600088815261010660209081526040808320805460ff19166001179055610107825291829020899055815189815290810188905263ffffffff85168183015261ffff84166060820152905189916001600160a01b038c16917fe235603860e031bbbc9226d101fa83a2a56a9ac8a576441e08de342faed03a58916080908290030190a3505050505050505050565b60008061299f613d94565b90506129aa60995490565b6129d5577f000000000000000000000000000000000000000000000000000000000000000091505090565b612a03817f0000000000000000000000000000000000000000000000000000000000000000611aa460995490565b91505090565b612a11614620565b61010c55565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612a785760405162461bcd60e51b8152600401610d6e9060208082526004908201526327aa2b1960e11b604082015260600190565b60008481526101066020526040902054849060ff161515600114612ac45760405162461bcd60e51b8152602060048201526003602482015262424e4160e81b6044820152606401610d6e565b6000858152610107602052604081205490818510612ae25781612ae4565b845b90508061010760008981526020019081526020016000206000828254612b0a91906159c0565b92505081905550806101026000828254612b249190615870565b92505081905550836101046000828254612b3e9190615870565b9091555060009050828610612b5c57612b5783876159c0565b612b5f565b60005b9050806101036000828254612b749190615870565b9091555050610102546101045460408051898152602081018990529081019290925260608201526001600160a01b0388169089907f096eee4238d7fc8b087bfbce1d8c5019025fcdd6db735aa0c1810ab450ccc81d9060800160405180910390a35050505050505050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6391906156c2565b15612c805760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff1615612ca45760405162461bcd60e51b8152600401610d6e906156fb565b612cac61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015612d14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d3891906156c2565b612d545760405162461bcd60e51b8152600401610d6e90615949565b612d5d846131c3565b915060008211612d6c57600080fd5b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612db5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612dd99190615911565b60fc54909150612df4906001600160a01b0316333086614598565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612e3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e619190615911565b9050612e6d8483615870565b8114612ea05760405162461bcd60e51b81526020600482015260026024820152612a2160f11b6044820152606401610d6e565b8360ff6000828254612eb29190615870565b90915550612ec290508587614603565b6101095460ff16612f53576033546001600160a01b03163314612f0c5760405162461bcd60e51b8152602060048201526002602482015261494360f01b6044820152606401610d6e565b620f4240861015612f445760405162461bcd60e51b8152602060048201526002602482015261495360f01b6044820152606401610d6e565b610109805460ff191660011790555b60408051858152602081018890526001600160a01b0387169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d79101611e68565b6060609b8054610dbe90615716565b60003381612fb38286613bae565b9050838110156130135760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d6e565b6130208286868403613e6f565b506001949350505050565b600061306561303983611a6a565b6101055461305b9061ffff600160401b8204811691600160501b900416615a57565b61ffff1690614a94565b61010554610e549190600160401b900461ffff16615a7a565b600033610f898185856141fe565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061311091906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015613157573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061317b91906156c2565b6131975760405162461bcd60e51b8152600401610d6e906156df565b61010e5460ff16156131bb5760405162461bcd60e51b8152600401610d6e906156fb565b610dac614aa6565b6000610e5482610fa1611e91565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613231573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061325591906156c2565b156132725760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156132965760405162461bcd60e51b8152600401610d6e906156fb565b61329e61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015613306573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061332a91906156c2565b6133465760405162461bcd60e51b8152600401610d6e90615949565b61334f85610f93565b91506000821161335e57600080fd5b6001600160a01b038316600090815260c9602052604090205461010a546133859082615870565b4210156133b95760405162461bcd60e51b8152602060048201526002602482015261535760f01b6044820152606401610d6e565b336001600160a01b038516146133f65760405162461bcd60e51b8152602060048201526002602482015261554160f01b6044820152606401610d6e565b6134008484614adc565b8561010060008282546134139190615870565b909155505060fc5461342f906001600160a01b03168688614ae6565b60408051878152602081018590526001600160a01b03808716929088169183917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db91015b60405180910390a450506116706001606555565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061350b91906156c2565b156135285760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff161561354c5760405162461bcd60e51b8152600401610d6e906156fb565b61355461453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b03821690639df10fe0906024016020604051808303816000875af11580156135bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135e091906156c2565b6135fc5760405162461bcd60e51b8152600401610d6e90615949565b6000851161360957600080fd5b61361585610e4f611e91565b9150336001600160a01b038416146136545760405162461bcd60e51b8152602060048201526002602482015261554160f01b6044820152606401610d6e565b6001600160a01b038316600090815260c9602052604090205461010a5461367b9082615870565b4210156136af5760405162461bcd60e51b815260206004820152600260248201526129a960f11b6044820152606401610d6e565b6136b98487614adc565b8261010060008282546136cc9190615870565b909155505060fc546136e8906001600160a01b03168685614ae6565b60408051848152602081018890526001600160a01b03808716929088169183917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db9101613473565b6000610e5482610e4f612994565b60008073fddcec68cfa40c38faf05f918484fc416a221bff63caf0f033846040518263ffffffff1660e01b81526004016137789190615aa0565b602060405180830381865af4158015613795573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137b99190615911565b9050600061010c546000146137da576137d58261010c546143e9565b6118ce565b5092915050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561383f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061386391906156c2565b156138805760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156138a45760405162461bcd60e51b8152600401610d6e906156fb565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635426adf06040518163ffffffff1660e01b8152600401602060405180830381865afa158015613904573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061392891906156a5565b60fc5460405163f3fef3a360e01b81526001600160a01b0391821660048201526024810185905291925082169063f3fef3a390604401600060405180830381600087803b15801561397857600080fd5b505af115801561398c573d6000803e3d6000fd5b50506040518492507fa0dae38c2f0a9884eb9f552aaef81b3026f43a0bf6721c92a8a6a1e623a583bb9150600090a25050565b61010e5460009060ff16156139d657506000919050565b6001600160a01b0382166000908152609760205260408120546139f890610e41565b60fc546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015613a46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a6a9190615911565b90506118ce82826143e9565b610105546000908190613a959061ffff16613a8f613d94565b90614a94565b90506000613aa1614466565b9050808211613ab35760009250505090565b613abd81836159c0565b9250505090565b61010e5460009060ff1615613adb57506000919050565b6001600160a01b03821660009081526097602090815260408083205460c99092529091205461010a54613b0e9082615870565b4211613b1e575060009392505050565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015613b67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b8b9190615911565b90506000613b9882613730565b9050613ba484826143e9565b9695505050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b613be1614620565b6001600160a01b038116613c465760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610d6e565b610dac8161467a565b6000610c5e61010d547f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f54074446040518163ffffffff1660e01b8152600401602060405180830381865afa158015613cb6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122b89190615911565b60008082118015613cea57508142115b613d1c5760405162461bcd60e51b815260206004820152600360248201526213111560ea1b6044820152606401610d6e565b6000613d2883426159c0565b90506000613d398262012a70615a18565b905061270f19811215613d4c575061270f195b612710613d598287615b12565b613d639190615b97565b95945050505050565b600080613d7883611822565b6101055490915061167090829062010000900461ffff16614a94565b6000806101005461010354610108546101045460ff54613db491906159d7565b613dbe91906159d7565b613dc891906159d7565b613dd29190615a18565b905060008113613de3576000612a03565b919050565b61010e805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600081613e4257506000610e54565b611670837f0000000000000000000000000000000000000000000000000000000000000000846000614b16565b6001600160a01b038316613ed15760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d6e565b6001600160a01b038216613f325760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d6e565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600081613fa257506000610e54565b611670837f0000000000000000000000000000000000000000000000000000000000000000846001614b16565b61010e805461ff00191690557f45e8904e0b531ccdf574f863b130fbc6a6db705232b7f4be2234210a8aea223a33613e16565b600054610100900460ff166140295760405162461bcd60e51b8152600401610d6e90615bc5565b611e8f614b67565b600054610100900460ff166140585760405162461bcd60e51b8152600401610d6e90615bc5565b6000826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa158015614098573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526140c09190810190615c10565b90506000826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa158015614102573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261412a9190810190615c10565b905060008282604051602001614141929190615ca4565b604051602081830303815290604052905060008383604051602001614167929190615cf4565b60405160208183030381529060405290506141828282614b97565b505050505050565b60006141968484613bae565b9050600019811461164b57818110156141f15760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d6e565b61164b8484848403613e6f565b6001600160a01b0383166142625760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d6e565b6001600160a01b0382166142c45760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d6e565b6001600160a01b0383166000908152609760205260409020548181101561433c5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d6e565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9061439c9086815260200190565b60405180910390a361164b848484614bc8565b61010e805462ff00001916620100001790557f1fa341bf3a791b4170c6687264b83465ed1766070ff2ad6285aff11d9b655feb613e163390565b60008183106143f85781611670565b5090919050565b6000611670837f0000000000000000000000000000000000000000000000000000000000000000846001614b16565b61010e805461ff0019166101001790557f3be817a47975a42676f4f105c01c2a28cfe5beff506ea96d3c8976015979d349613e163390565b60006101015461010254111561447c5750600090565b6101025461010154610c5e91906159c0565b6000808060001985870985870292508281108382030391505080600014156144c9578382816144bf576144bf615996565b0492505050611670565b8084116144d557600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600260655414156145915760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610d6e565b6002606555565b6040516001600160a01b038085166024830152831660448201526064810182905261164b9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614bd7565b61460d8282614ca9565b801561461c5761461c82614d72565b5050565b6033546001600160a01b03163314611e8f5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d6e565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b61010e805462ff0000191690557f2806498d544852f5dffa907ec16b104761ba682aefd1fb7ffc48d494dbe86cfd33613e16565b60405163e0d3d58d60e01b8152600481018290526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063e0d3d58d9060240161010060405180830381865afa158015614769573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061478d9190615d30565b509198975050505050505050565b604051631042b85f60e01b815260048101829052426024820152600090819081906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690631042b85f906044016040805180830381865afa15801561480c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148309190615dd0565b8051602090910151909590945092505050565b60008183116143f85781611670565b60008082121561486a5761486582615e1f565b610e54565b5090565b8015806148e85750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa1580156148c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148e69190615911565b155b6149535760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d6e565b6040516001600160a01b03831660248201526044810182905261260790849063095ea7b360e01b906064016145cc565b6040516315196bad60e31b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a8cb5d68906024016060604051808303816000875af11580156149ea573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614a0e9190615e3c565b5050604051638fa40d8960e01b8152600481018390523060248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169150638fa40d8990604401600060405180830381600087803b158015614a7957600080fd5b505af1158015614a8d573d6000803e3d6000fd5b5050505050565b6000611670838361ffff166002614dc6565b61010e805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613e163390565b61460d8282614de5565b6040516001600160a01b03831660248201526044810182905261260790849063a9059cbb60e01b906064016145cc565b600080614b2486868661448e565b90506001836002811115614b3a57614b3a6154b8565b148015614b57575060008480614b5257614b52615996565b868809115b15613d6357613ba4600182615870565b600054610100900460ff16614b8e5760405162461bcd60e51b8152600401610d6e90615bc5565b611e8f3361467a565b600054610100900460ff16614bbe5760405162461bcd60e51b8152600401610d6e90615bc5565b61461c8282614f20565b80156126075761260783614d72565b6000614c2c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614f6e9092919063ffffffff16565b8051909150156126075780806020019051810190614c4a91906156c2565b6126075760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d6e565b6001600160a01b038216614cff5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d6e565b8060996000828254614d119190615870565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a361461c60008383614bc8565b6001600160a01b038116600081815260c96020908152604091829020429081905591519182527f67aa0649fcf8ca9db5d63dfaf61ef0d90b143c59875cf40cc852103787c82e39910160405180910390a250565b6000614dd182614f7d565b614ddb8486615977565b6118ce91906159ac565b6001600160a01b038216614e455760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d6e565b6001600160a01b03821660009081526097602052604090205481811015614eb95760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d6e565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a361260783600084614bc8565b600054610100900460ff16614f475760405162461bcd60e51b8152600401610d6e90615bc5565b8151614f5a90609a90602085019061510b565b50805161260790609b90602084019061510b565b60606118ce8484600085614f95565b6000614f8a82600a615f4e565b610e54906064615977565b606082471015614ff65760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d6e565b600080866001600160a01b031685876040516150129190615f5a565b60006040518083038185875af1925050503d806000811461504f576040519150601f19603f3d011682016040523d82523d6000602084013e615054565b606091505b509150915061506587838387615070565b979650505050505050565b606083156150dc5782516150d5576001600160a01b0385163b6150d55760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d6e565b50816118ce565b6118ce83838151156150f15781518083602001fd5b8060405162461bcd60e51b8152600401610d6e91906151c7565b82805461511790615716565b90600052602060002090601f016020900481019282615139576000855561517f565b82601f1061515257805160ff191683800117855561517f565b8280016001018555821561517f579182015b8281111561517f578251825591602001919060010190615164565b5061486a9291505b8082111561486a5760008155600101615187565b60005b838110156151b657818101518382015260200161519e565b8381111561164b5750506000910152565b60208152600082518060208401526151e681604085016020870161519b565b601f01601f19169190910160400192915050565b60006020828403121561520c57600080fd5b5035919050565b6001600160a01b0381168114610dac57600080fd5b6000806040838503121561523b57600080fd5b823561524681615213565b946020939093013593505050565b600080600083850361012081121561526b57600080fd5b6101008082121561527b57600080fd5b859450840135905067ffffffffffffffff8082111561529957600080fd5b818601915086601f8301126152ad57600080fd5b8135818111156152bc57600080fd5b87602060a0830285010111156152d157600080fd5b6020830194508093505050509250925092565b6000806000606084860312156152f957600080fd5b833561530481615213565b9250602084013561531481615213565b929592945050506040919091013590565b60006020828403121561533757600080fd5b813561167081615213565b6000806040838503121561535557600080fd5b82359150602083013561536781615213565b809150509250929050565b6000806040838503121561538557600080fd5b50508035926020909101359150565b63ffffffff81168114610dac57600080fd5b803561ffff81168114613de357600080fd5b600080600080600080600080610100898b0312156153d557600080fd5b88356153e081615213565b9750602089013596506040890135955060608901359450608089013561540581615213565b935060a0890135925060c089013561541c81615394565b915061542a60e08a016153a6565b90509295985092959890939650565b6000806000806080858703121561544f57600080fd5b84359350602085013561546181615213565b93969395505050506040820135916060013590565b60008060006060848603121561548b57600080fd5b83359250602084013561549d81615213565b915060408401356154ad81615213565b809150509250925092565b634e487b7160e01b600052602160045260246000fd5b60208101600883106154f057634e487b7160e01b600052602160045260246000fd5b91905290565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff8111828210171561552f5761552f6154f6565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561555e5761555e6154f6565b604052919050565b8015158114610dac57600080fd5b6000602080838503121561558757600080fd5b823567ffffffffffffffff8082111561559f57600080fd5b818501915085601f8301126155b357600080fd5b8135818111156155c5576155c56154f6565b6155d3848260051b01615535565b818152848101925060a09182028401850191888311156155f257600080fd5b938501935b8285101561566b5780858a03121561560f5760008081fd5b61561761550c565b853561562281615213565b81528587013561563181615566565b8188015260408681013561564481615394565b908201526060868101359082015260808087013590820152845293840193928501926155f7565b50979650505050505050565b6000806040838503121561568a57600080fd5b823561569581615213565b9150602083013561536781615213565b6000602082840312156156b757600080fd5b815161167081615213565b6000602082840312156156d457600080fd5b815161167081615566565b60208082526002908201526104f560f41b604082015260600190565b6020808252600190820152600560fc1b604082015260600190565b600181811c9082168061572a57607f821691505b6020821081141561574b57634e487b7160e01b600052602260045260246000fd5b50919050565b60006020828403121561576357600080fd5b813561167081615394565b60006020828403121561578057600080fd5b611670826153a6565b634e487b7160e01b600052603260045260246000fd5b81356157aa81615213565b81546001600160a01b031981166001600160a01b0392909216918217835560208401356157d681615566565b60ff60a01b90151560a01b166001600160a81b03198216831781178455604085013561580181615394565b6001600160c81b0319929092169092179190911760a89190911b63ffffffff60a81b1617815560608201356001820155608090910135600290910155565b634e487b7160e01b600052601160045260246000fd5b60006000198214156158695761586961583f565b5060010190565b600082198211156158835761588361583f565b500190565b60006020808301818452808554808352604092508286019150866000528360002060005b828110156159045781546001600160a01b038116855260a081811c60ff1615158887015260a89190911c63ffffffff1686860152600180840154606087015260028401546080870152940193600390920191016158ac565b5091979650505050505050565b60006020828403121561592357600080fd5b5051919050565b60208082526005908201526405343465f560dc1b604082015260600190565b60208082526014908201527313dc9858db194e88139bdd08105c1c1c9bdd995960621b604082015260600190565b60008160001904831182151516156159915761599161583f565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826159bb576159bb615996565b500490565b6000828210156159d2576159d261583f565b500390565b600080821280156001600160ff1b03849003851316156159f9576159f961583f565b600160ff1b8390038412811615615a1257615a1261583f565b50500190565b60008083128015600160ff1b850184121615615a3657615a3661583f565b6001600160ff1b0384018313811615615a5157615a5161583f565b50500390565b600061ffff83811690831681811015615a7257615a7261583f565b039392505050565b600061ffff808316818516808303821115615a9757615a9761583f565b01949350505050565b602080825282518282018190526000919060409081850190868401855b8281101561590457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101615abd565b60006001600160ff1b0381841382841380821686840486111615615b3857615b3861583f565b600160ff1b6000871282811687830589121615615b5757615b5761583f565b60008712925087820587128484161615615b7357615b7361583f565b87850587128184161615615b8957615b8961583f565b505050929093029392505050565b600082615ba657615ba6615996565b600160ff1b821460001984141615615bc057615bc061583f565b500590565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b600060208284031215615c2257600080fd5b815167ffffffffffffffff80821115615c3a57600080fd5b818401915084601f830112615c4e57600080fd5b815181811115615c6057615c606154f6565b615c73601f8201601f1916602001615535565b9150808252856020828501011115615c8a57600080fd5b615c9b81602084016020860161519b565b50949350505050565b60008351615cb681846020880161519b565b602d60f81b9083019081528351615cd481600184016020880161519b565b662073686172657360c81b60019290910191820152600801949350505050565b60008351615d0681846020880161519b565b602d60f81b9083019081528351615d2481600184016020880161519b565b01600101949350505050565b600080600080600080600080610100898b031215615d4d57600080fd5b8851615d5881615213565b60208a0151909850615d6981615213565b60408a015160608b01519198509650615d8181615213565b60808a015160a08b01519196509450615d9981615394565b60c08a0151909350615daa81615394565b60e08a015190925060078110615dbf57600080fd5b809150509295985092959890939650565b600060408284031215615de257600080fd5b6040516040810181811067ffffffffffffffff82111715615e0557615e056154f6565b604052825181526020928301519281019290925250919050565b6000600160ff1b821415615e3557615e3561583f565b5060000390565b600080600060608486031215615e5157600080fd5b8351925060208401519150604084015190509250925092565b600181815b80851115615ea5578160001904821115615e8b57615e8b61583f565b80851615615e9857918102915b93841c9390800290615e6f565b509250929050565b600082615ebc57506001610e54565b81615ec957506000610e54565b8160018114615edf5760028114615ee957615f05565b6001915050610e54565b60ff841115615efa57615efa61583f565b50506001821b610e54565b5060208310610133831016604e8410600b8410161715615f28575081810a610e54565b615f328383615e6a565b8060001904821115615f4657615f4661583f565b029392505050565b60006116708383615ead565b60008251615f6c81846020870161519b565b919091019291505056fea26469706673582212205dd074caf08c3376323c04f8f0d2ea3c433bdabbb0d3296aae3ab84d9cc5ddf764736f6c634300080b0033000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282290000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb000000000000000000000000203e8740894c8955cb8950759876d7e7e45e04c1
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061050f5760003560e01c80637701a84c116102a4578063ba08765211610172578063ded7abc6116100d9578063f57781fe11610092578063f57781fe14610bc2578063f73e5aab14610bd5578063f84d68fd14610bfc578063f87bc1c814610c10578063fa4c1d5a14610c1a578063fa83a97614610c4157600080fd5b8063ded7abc614610b81578063e07baba614610b94578063ef8b30f714610abe578063f2fde38b14610b9e578063f319986114610bb1578063f540744414610bba57600080fd5b8063ce96cb771161012b578063ce96cb7714610b06578063d24bc1a414610b19578063d2c76fd814610b40578063d905777e14610b48578063dbc162de14610b5b578063dd62ed3e14610b6e57600080fd5b8063ba08765214610aab578063c63d75b614610682578063c6e6f59214610abe578063c84f95dd14610ad1578063ca0c1bb014610ae0578063cc9ce35a14610af357600080fd5b8063a457c2d711610216578063ac6787bb116101cf578063ac6787bb14610a3d578063b2016bd414610a53578063b3d7f6b914610a66578063b460af9414610a79578063b4cebd5714610a8c578063b4eae1cb14610a9657600080fd5b8063a457c2d7146109cd578063a4be77ee146109e0578063a5c2f9c4146109f9578063a7fc093d14610a0c578063a9059cbb14610a22578063aa09d5b714610a3557600080fd5b80638da5cb5b116102685780638da5cb5b14610940578063913ff9a91461095157806391bf279b1461096457806394bf804d1461098b57806395d89b411461099e578063a11ea0ed146109a657600080fd5b80637701a84c146108fe5780637faf15621461091157806380bde5ac14610919578063846be29e1461092c5780638b1908601461093657600080fd5b8063475d9694116103e1578063667a65d911610353578063715018a61161030c578063715018a61461088357806371f3ec561461088b578063739dd659146108b457806373aa6b57146108bc578063764f5963146108c457806376f28daf146108eb57600080fd5b8063667a65d9146107f5578063672b0774146108085780636d483fe61461082c5780636e553f651461083d5780636f7833131461085057806370a082311461085a57600080fd5b8063568ef470116103a5578063568ef470146107365780635932f4ff1461073e5780635bb2c822146107665780635c975abb146107705780636051f2101461077e5780636298deab146107a557600080fd5b8063475d9694146106d757806349c3d6e6146106df5780634b1dd53b146107065780634cdad5061461054e578063562d75381461070f57600080fd5b80631d42a60e11610485578063395093511161043e578063395093511461064d5780633f9be66614610660578063402d267d14610682578063424ddc4a14610695578063439d766d146106bc5780634523d6f7146106c457600080fd5b80631d42a60e146105d257806323b872dd146105e5578063280e32fb146105f8578063313ce5671461061d578063318213081461062c57806338d52e0f146105f857600080fd5b8063095ea7b3116104d7578063095ea7b3146105745780630a28a477146105975780631446cc24146105aa578063167c6314146105b457806318160ddd146105bc5780631d24a6e4146105c457600080fd5b806301e1d11414610514578063068cc5141461052f57806306fdde031461053957806307a2d13a1461054e57806308a6355a14610561575b600080fd5b61051c610c54565b6040519081526020015b60405180910390f35b610537610c63565b005b610541610daf565b60405161052691906151c7565b61051c61055c3660046151fa565b610e41565b61053761056f3660046151fa565b610e5a565b610587610582366004615228565b610f7b565b6040519015158152602001610526565b61051c6105a53660046151fa565b610f93565b61051c6101005481565b610537610fa6565b60995461051c565b610109546105879060ff1681565b6105376105e0366004615254565b6110e1565b6105876105f33660046152e4565b611651565b60fc546001600160a01b03165b6040516001600160a01b039091168152602001610526565b60405160128152602001610526565b61051c61063a3660046151fa565b6101076020526000908152604090205481565b61058761065b366004615228565b611677565b6101055461066f9061ffff1681565b60405161ffff9091168152602001610526565b61051c610690366004615325565b611699565b61051c7f0000000000000000000000000000000000000000000000000de0b6b3a764000081565b6105376116e5565b61051c6106d23660046151fa565b611822565b6105376118d6565b6106057f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb81565b6101085461051c565b61051c7f000000000000000000000000000000000000000000000000000000000000012c81565b60fe5461051c565b61010554640100000000900463ffffffff165b60405163ffffffff9091168152602001610526565b61051c6101035481565b61010e546105879060ff1681565b6106057f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb2822981565b6107b86107b33660046151fa565b611a12565b604080516001600160a01b039096168652931515602086015263ffffffff909216928401929092526060830191909152608082015260a001610526565b61066f6108033660046151fa565b611a6a565b6105876108163660046151fa565b6101066020526000908152604090205460ff1681565b60fd546001600160a01b0316610605565b61051c61084b366004615342565b611ab1565b61051c6101045481565b61051c610868366004615325565b6001600160a01b031660009081526097602052604090205490565b610537611e7d565b61051c610899366004615325565b6001600160a01b0316600090815260c9602052604090205490565b61051c611e91565b610537611ecf565b61051c7f0000000000000000000000000000000000c097ce7bc90715b34b9f100000000081565b6105376108f9366004615372565b612015565b61053761090c3660046153b8565b61260c565b61051c612994565b6105376109273660046151fa565b612a09565b61051c61010c5481565b61051c61010a5481565b6033546001600160a01b0316610605565b61053761095f366004615439565b612a17565b61051c7f000000000000000000000000000000000000000000000000000000000000000381565b61051c610999366004615342565b612bdf565b610541612f96565b61051c7f000000000000000000000000000000000000000100000000000000000000000081565b6105876109db366004615228565b612fa5565b6101055461075190640100000000900463ffffffff1681565b61066f610a073660046151fa565b61302b565b6101055461066f90600160501b900461ffff1681565b610587610a30366004615228565b61307e565b61053761308c565b6101055461066f90600160401b900461ffff1681565b60fd54610605906001600160a01b031681565b61051c610a743660046151fa565b6131c3565b61051c610a87366004615476565b6131d1565b61051c6101015481565b6101055461066f9062010000900461ffff1681565b61051c610ab9366004615476565b613487565b61051c610acc3660046151fa565b613730565b600160405161052691906154ce565b61051c610aee366004615574565b61373e565b610537610b013660046151fa565b6137e1565b61051c610b14366004615325565b6139bf565b6106057f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb81565b61051c613a76565b61051c610b56366004615325565b613ac4565b60fc54610605906001600160a01b031681565b61051c610b7c366004615677565b613bae565b61010e5461058790610100900460ff1681565b61051c61010d5481565b610537610bac366004615325565b613bd9565b61051c60ff5481565b61051c613c4f565b61051c610bd0366004615372565b613cda565b6106057f000000000000000000000000203e8740894c8955cb8950759876d7e7e45e04c181565b61010e546105879062010000900460ff1681565b61051c6101025481565b61051c7f000000000000000000000000000000000000000000000000000000000001518081565b61051c610c4f3660046151fa565b613d6c565b6000610c5e613d94565b905090565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce791906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015610d2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d5291906156c2565b610d775760405162461bcd60e51b8152600401610d6e906156df565b60405180910390fd5b61010e5460ff16610d9a5760405162461bcd60e51b8152600401610d6e906156fb565b610da44261010d55565b610dac613de8565b50565b6060609a8054610dbe90615716565b80601f0160208091040260200160405190810160405280929190818152602001828054610dea90615716565b8015610e375780601f10610e0c57610100808354040283529160200191610e37565b820191906000526020600020905b815481529060010190602001808311610e1a57829003601f168201915b5050505050905090565b6000610e5482610e4f611e91565b613e33565b92915050565b7f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610eb8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edc91906156a5565b6001600160a01b0316336001600160a01b031614610f215760405162461bcd60e51b81526020600482015260026024820152614f4f60f01b6044820152606401610d6e565b7f00000000000000000000000000000000000000000000000000000000000151808110610f755760405162461bcd60e51b815260206004820152600260248201526115d160f21b6044820152606401610d6e565b61010a55565b600033610f89818585613e6f565b5060019392505050565b6000610e5482610fa1612994565b613f93565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611006573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102a91906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015611071573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061109591906156c2565b6110b15760405162461bcd60e51b8152600401610d6e906156df565b61010e54610100900460ff166110d95760405162461bcd60e51b8152600401610d6e906156fb565b610dac613fcf565b600054610100900460ff16158080156111015750600054600160ff909116105b8061111b5750303b15801561111b575060005460ff166001145b61117e5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d6e565b6000805460ff1916600117905580156111a1576000805461ff0019166101001790555b6111a9614002565b6111ce6111b96020860186615325565b6111c96040870160208801615325565b614031565b6111db6020850185615325565b60fc80546001600160a01b0319166001600160a01b039290921691909117905561120b6040850160208601615325565b60fd80546001600160a01b0319166001600160a01b0392831617905560408581013560fe8190557f000000000000000000000000000000000000000000000000000000000000012c61010a559051630ba4ccb560e21b815260048101919091527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb821660248201527f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb2822990911690632e9332d490604401600060405180830381600087803b1580156112db57600080fd5b505af11580156112ef573d6000803e3d6000fd5b50611304925050506080850160608601615751565b610105805463ffffffff929092166401000000000267ffffffff000000001990921691909117905561133c60a085016080860161576e565b610105805461ffff92909216600160401b0269ffff00000000000000001990921691909117905561137360c0850160a0860161576e565b610105805461ffff60501b1916600160501b61ffff9384168102919091179182905581048216600160401b90910490911611156113db5760405162461bcd60e51b8152600401610d6e9060208082526004908201526324a9262160e11b604082015260600190565b6113eb60e0850160c0860161576e565b610105805461ffff191661ffff92909216919091179055611413610100850160e0860161576e565b610105805461ffff928316620100000263ffff0000198216811790925561271091831692169190911711156114735760405162461bcd60e51b8152600401610d6e906020808252600490820152630494c54560e41b604082015260600190565b60005b828110156114d65761010b84848381811061149357611493615789565b83546001810185556000948552602090942060a0909102929092019260030290910190506114c1828261579f565b505080806114ce90615855565b915050611476565b5061010b546001118015906114ef575061010b54600210155b6115215760405162461bcd60e51b815260206004820152600360248201526214149360ea1b6044820152606401610d6e565b6115316040850160208601615325565b6001600160a01b03166115476020860186615325565b6001600160a01b03167f39a60e55b000e31daa0c5bae68cfc6256176f9ae4e9fa343e5224410a69c1ebb60408701356115866080890160608a01615751565b61159660a08a0160808b0161576e565b6115a660c08b0160a08c0161576e565b6115b660e08c0160c08d0161576e565b6115c76101008d0160e08e0161576e565b6040805196875263ffffffff95909516602087015261ffff938416868601529183166060860152821660808501521660a0830152519081900360c00190a3801561164b576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60003361165f85828561418a565b61166a8585856141fe565b60019150505b9392505050565b600033610f8981858561168a8383613bae565b6116949190615870565b613e6f565b61010e5460009060ff16156116b057506000919050565b6101095460ff161580156116cf57506033546001600160a01b03163314155b156116dc57506000919050565b50600019919050565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611745573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176991906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa1580156117b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d491906156c2565b6117f05760405162461bcd60e51b8152600401610d6e906156df565b61010e5462010000900460ff161561181a5760405162461bcd60e51b8152600401610d6e906156fb565b610dac6143af565b60008073fddcec68cfa40c38faf05f918484fc416a221bff63caf0f03361010b6040518263ffffffff1660e01b815260040161185e9190615888565b602060405180830381865af415801561187b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061189f9190615911565b9050600061010c546000146118c0576118bb8261010c546143e9565b6118c2565b815b90506118ce84826143ff565b949350505050565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611936573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061195a91906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa1580156119a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c591906156c2565b6119e15760405162461bcd60e51b8152600401610d6e906156df565b61010e54610100900460ff1615611a0a5760405162461bcd60e51b8152600401610d6e906156fb565b610dac61442e565b61010b8181548110611a2357600080fd5b60009182526020909120600390910201805460018201546002909201546001600160a01b0382169350600160a01b820460ff1692600160a81b90920463ffffffff16919085565b6000611a74613d94565b611a8057506000919050565b610e54611aa983611a8f614466565b611a999190615870565b612710611aa4613d94565b61448e565b6127106143e9565b60007f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b3591906156c2565b15611b525760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff1615611b765760405162461bcd60e51b8152600401610d6e906156fb565b611b7e61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015611be6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c0a91906156c2565b611c265760405162461bcd60e51b8152600401610d6e90615949565b60008411611c3357600080fd5b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611c7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca09190615911565b60fc54909150611cbb906001600160a01b0316333088614598565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611d04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d289190615911565b9050611d348683615870565b8114611d675760405162461bcd60e51b81526020600482015260026024820152612a2160f11b6044820152606401610d6e565b611d7386610e4f612994565b93508560ff6000828254611d879190615870565b90915550611d9790508585614603565b6101095460ff16611e29576033546001600160a01b03163314611de25760405162461bcd60e51b815260206004820152600360248201526246444d60e81b6044820152606401610d6e565b620f4240841015611e1a5760405162461bcd60e51b8152602060048201526002602482015261495360f01b6044820152606401610d6e565b610109805460ff191660011790555b60408051878152602081018690526001600160a01b0387169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d791015b60405180910390a3505050610e546001606555565b611e85614620565b611e8f600061467a565b565b6000611e9b612994565b611ec57f0000000000000000000000000000000000c097ce7bc90715b34b9f100000000080615977565b610c5e91906159ac565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f2f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f5391906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015611f9a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbe91906156c2565b611fda5760405162461bcd60e51b8152600401610d6e906156df565b61010e5462010000900460ff166120035760405162461bcd60e51b8152600401610d6e906156fb565b61200d4261010d55565b610dac6146cc565b7f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612073573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061209791906156c2565b156120b45760405162461bcd60e51b8152600401610d6e9061592a565b61010e5462010000900460ff16156120de5760405162461bcd60e51b8152600401610d6e906156fb565b61010e5460ff16156121025760405162461bcd60e51b8152600401610d6e906156fb565b60008281526101066020526040902054829060ff16151560011461214e5760405162461bcd60e51b8152602060048201526003602482015262424e4160e81b6044820152606401610d6e565b61215661453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb906001600160a01b03821690639df10fe0906024016020604051808303816000875af11580156121be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e291906156c2565b6121fe5760405162461bcd60e51b8152600401610d6e90615949565b600061220985614700565b90506000806122178761479b565b604051634b67a05b60e11b8152600481018a905291935091506000906001600160a01b037f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb2822916906396cf40b690602401602060405180830381865afa158015612284573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122a89190615911565b905060006122bd826122b8613c4f565b614843565b905060006122cb8683613cda565b9050808912156123035760405162461bcd60e51b815260206004820152600360248201526215105160ea1b6044820152606401610d6e565b60008113156124c057600061231782614852565b905060006123a9827f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b031663f8cbc5d66040518163ffffffff1660e01b8152600401602060405180830381865afa15801561237d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123a19190615911565b61271061448e565b90506123d93330836123bb868c615870565b6123c591906159c0565b60fc546001600160a01b0316929190614598565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b03166372c8fc0e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612439573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061245d91906156a5565b9050811561247d5760fc5461247d906001600160a01b0316338385614598565b8761010260008282546124909190615870565b909155506124a0905082846159c0565b61010860008282546124b291906159d7565b909155506125399350505050565b60006124cb82614852565b9050858111156124d85750845b60006124e482886159c0565b905080156125045760fc54612504906001600160a01b0316333084614598565b8661010260008282546125179190615870565b925050819055508161010860008282546125319190615a18565b909155505050505b604051630da8959360e01b8152600481018b90523360248201527f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031690630da8959390604401600060405180830381600087803b1580156125a157600080fd5b505af11580156125b5573d6000803e3d6000fd5b505060408051888152602081018d90523393508d92507f274d762f568e6bddf149314ec29fac2cc57609d38374d13f92dad87efa588387910160405180910390a3505050505050506126076001606555565b505050565b336001600160a01b037f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb161461266d5760405162461bcd60e51b8152600401610d6e9060208082526004908201526327a9a1a360e11b604082015260600190565b7f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126ef91906156c2565b1561270c5760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156127305760405162461bcd60e51b8152600401610d6e906156fb565b61010e54610100900460ff16156127595760405162461bcd60e51b8152600401610d6e906156fb565b60fd546001600160a01b0385811691161461279f5760405162461bcd60e51b8152600401610d6e90602080825260049082015263135350d560e21b604082015260600190565b6127a88661302b565b61ffff168161ffff1610156127e55760405162461bcd60e51b815260206004820152600360248201526224a4a960e91b6044820152606401610d6e565b6101055463ffffffff640100000000909104811690831611156128305760405162461bcd60e51b815260206004820152600360248201526213135160ea1b6044820152606401610d6e565b85612839613a76565b101561286d5760405162461bcd60e51b815260206004820152600360248201526204c4d560ec1b6044820152606401610d6e565b600061287887613d6c565b9050808610156128ae5760405162461bcd60e51b81526020600482015260016024820152604360f81b6044820152606401610d6e565b60fc546128e5906001600160a01b03167f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282298961486e565b6128ee88614983565b8661010160008282546129019190615870565b9091555050600088815261010660209081526040808320805460ff19166001179055610107825291829020899055815189815290810188905263ffffffff85168183015261ffff84166060820152905189916001600160a01b038c16917fe235603860e031bbbc9226d101fa83a2a56a9ac8a576441e08de342faed03a58916080908290030190a3505050505050505050565b60008061299f613d94565b90506129aa60995490565b6129d5577f0000000000000000000000000000000000c097ce7bc90715b34b9f100000000091505090565b612a03817f0000000000000000000000000000000000c097ce7bc90715b34b9f1000000000611aa460995490565b91505090565b612a11614620565b61010c55565b336001600160a01b037f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282291614612a785760405162461bcd60e51b8152600401610d6e9060208082526004908201526327aa2b1960e11b604082015260600190565b60008481526101066020526040902054849060ff161515600114612ac45760405162461bcd60e51b8152602060048201526003602482015262424e4160e81b6044820152606401610d6e565b6000858152610107602052604081205490818510612ae25781612ae4565b845b90508061010760008981526020019081526020016000206000828254612b0a91906159c0565b92505081905550806101026000828254612b249190615870565b92505081905550836101046000828254612b3e9190615870565b9091555060009050828610612b5c57612b5783876159c0565b612b5f565b60005b9050806101036000828254612b749190615870565b9091555050610102546101045460408051898152602081018990529081019290925260608201526001600160a01b0388169089907f096eee4238d7fc8b087bfbce1d8c5019025fcdd6db735aa0c1810ab450ccc81d9060800160405180910390a35050505050505050565b60007f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6391906156c2565b15612c805760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff1615612ca45760405162461bcd60e51b8152600401610d6e906156fb565b612cac61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015612d14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d3891906156c2565b612d545760405162461bcd60e51b8152600401610d6e90615949565b612d5d846131c3565b915060008211612d6c57600080fd5b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612db5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612dd99190615911565b60fc54909150612df4906001600160a01b0316333086614598565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612e3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e619190615911565b9050612e6d8483615870565b8114612ea05760405162461bcd60e51b81526020600482015260026024820152612a2160f11b6044820152606401610d6e565b8360ff6000828254612eb29190615870565b90915550612ec290508587614603565b6101095460ff16612f53576033546001600160a01b03163314612f0c5760405162461bcd60e51b8152602060048201526002602482015261494360f01b6044820152606401610d6e565b620f4240861015612f445760405162461bcd60e51b8152602060048201526002602482015261495360f01b6044820152606401610d6e565b610109805460ff191660011790555b60408051858152602081018890526001600160a01b0387169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d79101611e68565b6060609b8054610dbe90615716565b60003381612fb38286613bae565b9050838110156130135760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d6e565b6130208286868403613e6f565b506001949350505050565b600061306561303983611a6a565b6101055461305b9061ffff600160401b8204811691600160501b900416615a57565b61ffff1690614a94565b61010554610e549190600160401b900461ffff16615a7a565b600033610f898185856141fe565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b031663352f43006040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061311091906156a5565b60405163237dfb4760e11b81523360048201529091506001600160a01b038216906346fbf68e90602401602060405180830381865afa158015613157573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061317b91906156c2565b6131975760405162461bcd60e51b8152600401610d6e906156df565b61010e5460ff16156131bb5760405162461bcd60e51b8152600401610d6e906156fb565b610dac614aa6565b6000610e5482610fa1611e91565b60007f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613231573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061325591906156c2565b156132725760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156132965760405162461bcd60e51b8152600401610d6e906156fb565b61329e61453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb906001600160a01b03821690639df10fe0906024016020604051808303816000875af1158015613306573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061332a91906156c2565b6133465760405162461bcd60e51b8152600401610d6e90615949565b61334f85610f93565b91506000821161335e57600080fd5b6001600160a01b038316600090815260c9602052604090205461010a546133859082615870565b4210156133b95760405162461bcd60e51b8152602060048201526002602482015261535760f01b6044820152606401610d6e565b336001600160a01b038516146133f65760405162461bcd60e51b8152602060048201526002602482015261554160f01b6044820152606401610d6e565b6134008484614adc565b8561010060008282546134139190615870565b909155505060fc5461342f906001600160a01b03168688614ae6565b60408051878152602081018590526001600160a01b03808716929088169183917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db91015b60405180910390a450506116706001606555565b60007f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061350b91906156c2565b156135285760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff161561354c5760405162461bcd60e51b8152600401610d6e906156fb565b61355461453e565b6040516304ef887f60e51b81523360048201527f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb906001600160a01b03821690639df10fe0906024016020604051808303816000875af11580156135bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135e091906156c2565b6135fc5760405162461bcd60e51b8152600401610d6e90615949565b6000851161360957600080fd5b61361585610e4f611e91565b9150336001600160a01b038416146136545760405162461bcd60e51b8152602060048201526002602482015261554160f01b6044820152606401610d6e565b6001600160a01b038316600090815260c9602052604090205461010a5461367b9082615870565b4210156136af5760405162461bcd60e51b815260206004820152600260248201526129a960f11b6044820152606401610d6e565b6136b98487614adc565b8261010060008282546136cc9190615870565b909155505060fc546136e8906001600160a01b03168685614ae6565b60408051848152602081018890526001600160a01b03808716929088169183917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db9101613473565b6000610e5482610e4f612994565b60008073fddcec68cfa40c38faf05f918484fc416a221bff63caf0f033846040518263ffffffff1660e01b81526004016137789190615aa0565b602060405180830381865af4158015613795573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137b99190615911565b9050600061010c546000146137da576137d58261010c546143e9565b6118ce565b5092915050565b7f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561383f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061386391906156c2565b156138805760405162461bcd60e51b8152600401610d6e9061592a565b61010e5460ff16156138a45760405162461bcd60e51b8152600401610d6e906156fb565b60007f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b0316635426adf06040518163ffffffff1660e01b8152600401602060405180830381865afa158015613904573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061392891906156a5565b60fc5460405163f3fef3a360e01b81526001600160a01b0391821660048201526024810185905291925082169063f3fef3a390604401600060405180830381600087803b15801561397857600080fd5b505af115801561398c573d6000803e3d6000fd5b50506040518492507fa0dae38c2f0a9884eb9f552aaef81b3026f43a0bf6721c92a8a6a1e623a583bb9150600090a25050565b61010e5460009060ff16156139d657506000919050565b6001600160a01b0382166000908152609760205260408120546139f890610e41565b60fc546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015613a46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a6a9190615911565b90506118ce82826143e9565b610105546000908190613a959061ffff16613a8f613d94565b90614a94565b90506000613aa1614466565b9050808211613ab35760009250505090565b613abd81836159c0565b9250505090565b61010e5460009060ff1615613adb57506000919050565b6001600160a01b03821660009081526097602090815260408083205460c99092529091205461010a54613b0e9082615870565b4211613b1e575060009392505050565b60fc546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015613b67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b8b9190615911565b90506000613b9882613730565b9050613ba484826143e9565b9695505050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b613be1614620565b6001600160a01b038116613c465760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610d6e565b610dac8161467a565b6000610c5e61010d547f0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb6001600160a01b031663f54074446040518163ffffffff1660e01b8152600401602060405180830381865afa158015613cb6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122b89190615911565b60008082118015613cea57508142115b613d1c5760405162461bcd60e51b815260206004820152600360248201526213111560ea1b6044820152606401610d6e565b6000613d2883426159c0565b90506000613d398262012a70615a18565b905061270f19811215613d4c575061270f195b612710613d598287615b12565b613d639190615b97565b95945050505050565b600080613d7883611822565b6101055490915061167090829062010000900461ffff16614a94565b6000806101005461010354610108546101045460ff54613db491906159d7565b613dbe91906159d7565b613dc891906159d7565b613dd29190615a18565b905060008113613de3576000612a03565b919050565b61010e805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600081613e4257506000610e54565b611670837f0000000000000000000000000000000000c097ce7bc90715b34b9f1000000000846000614b16565b6001600160a01b038316613ed15760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d6e565b6001600160a01b038216613f325760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d6e565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600081613fa257506000610e54565b611670837f0000000000000000000000000000000000c097ce7bc90715b34b9f1000000000846001614b16565b61010e805461ff00191690557f45e8904e0b531ccdf574f863b130fbc6a6db705232b7f4be2234210a8aea223a33613e16565b600054610100900460ff166140295760405162461bcd60e51b8152600401610d6e90615bc5565b611e8f614b67565b600054610100900460ff166140585760405162461bcd60e51b8152600401610d6e90615bc5565b6000826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa158015614098573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526140c09190810190615c10565b90506000826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa158015614102573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261412a9190810190615c10565b905060008282604051602001614141929190615ca4565b604051602081830303815290604052905060008383604051602001614167929190615cf4565b60405160208183030381529060405290506141828282614b97565b505050505050565b60006141968484613bae565b9050600019811461164b57818110156141f15760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d6e565b61164b8484848403613e6f565b6001600160a01b0383166142625760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d6e565b6001600160a01b0382166142c45760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d6e565b6001600160a01b0383166000908152609760205260409020548181101561433c5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d6e565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9061439c9086815260200190565b60405180910390a361164b848484614bc8565b61010e805462ff00001916620100001790557f1fa341bf3a791b4170c6687264b83465ed1766070ff2ad6285aff11d9b655feb613e163390565b60008183106143f85781611670565b5090919050565b6000611670837f0000000000000000000000000000000000000000000000000de0b6b3a7640000846001614b16565b61010e805461ff0019166101001790557f3be817a47975a42676f4f105c01c2a28cfe5beff506ea96d3c8976015979d349613e163390565b60006101015461010254111561447c5750600090565b6101025461010154610c5e91906159c0565b6000808060001985870985870292508281108382030391505080600014156144c9578382816144bf576144bf615996565b0492505050611670565b8084116144d557600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600260655414156145915760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610d6e565b6002606555565b6040516001600160a01b038085166024830152831660448201526064810182905261164b9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614bd7565b61460d8282614ca9565b801561461c5761461c82614d72565b5050565b6033546001600160a01b03163314611e8f5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d6e565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b61010e805462ff0000191690557f2806498d544852f5dffa907ec16b104761ba682aefd1fb7ffc48d494dbe86cfd33613e16565b60405163e0d3d58d60e01b8152600481018290526000907f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b03169063e0d3d58d9060240161010060405180830381865afa158015614769573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061478d9190615d30565b509198975050505050505050565b604051631042b85f60e01b815260048101829052426024820152600090819081906001600160a01b037f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282291690631042b85f906044016040805180830381865afa15801561480c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148309190615dd0565b8051602090910151909590945092505050565b60008183116143f85781611670565b60008082121561486a5761486582615e1f565b610e54565b5090565b8015806148e85750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa1580156148c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148e69190615911565b155b6149535760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d6e565b6040516001600160a01b03831660248201526044810182905261260790849063095ea7b360e01b906064016145cc565b6040516315196bad60e31b8152600481018290527f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b03169063a8cb5d68906024016060604051808303816000875af11580156149ea573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614a0e9190615e3c565b5050604051638fa40d8960e01b8152600481018390523060248201527f000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282296001600160a01b03169150638fa40d8990604401600060405180830381600087803b158015614a7957600080fd5b505af1158015614a8d573d6000803e3d6000fd5b5050505050565b6000611670838361ffff166002614dc6565b61010e805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613e163390565b61460d8282614de5565b6040516001600160a01b03831660248201526044810182905261260790849063a9059cbb60e01b906064016145cc565b600080614b2486868661448e565b90506001836002811115614b3a57614b3a6154b8565b148015614b57575060008480614b5257614b52615996565b868809115b15613d6357613ba4600182615870565b600054610100900460ff16614b8e5760405162461bcd60e51b8152600401610d6e90615bc5565b611e8f3361467a565b600054610100900460ff16614bbe5760405162461bcd60e51b8152600401610d6e90615bc5565b61461c8282614f20565b80156126075761260783614d72565b6000614c2c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614f6e9092919063ffffffff16565b8051909150156126075780806020019051810190614c4a91906156c2565b6126075760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d6e565b6001600160a01b038216614cff5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d6e565b8060996000828254614d119190615870565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a361461c60008383614bc8565b6001600160a01b038116600081815260c96020908152604091829020429081905591519182527f67aa0649fcf8ca9db5d63dfaf61ef0d90b143c59875cf40cc852103787c82e39910160405180910390a250565b6000614dd182614f7d565b614ddb8486615977565b6118ce91906159ac565b6001600160a01b038216614e455760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d6e565b6001600160a01b03821660009081526097602052604090205481811015614eb95760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d6e565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a361260783600084614bc8565b600054610100900460ff16614f475760405162461bcd60e51b8152600401610d6e90615bc5565b8151614f5a90609a90602085019061510b565b50805161260790609b90602084019061510b565b60606118ce8484600085614f95565b6000614f8a82600a615f4e565b610e54906064615977565b606082471015614ff65760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d6e565b600080866001600160a01b031685876040516150129190615f5a565b60006040518083038185875af1925050503d806000811461504f576040519150601f19603f3d011682016040523d82523d6000602084013e615054565b606091505b509150915061506587838387615070565b979650505050505050565b606083156150dc5782516150d5576001600160a01b0385163b6150d55760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d6e565b50816118ce565b6118ce83838151156150f15781518083602001fd5b8060405162461bcd60e51b8152600401610d6e91906151c7565b82805461511790615716565b90600052602060002090601f016020900481019282615139576000855561517f565b82601f1061515257805160ff191683800117855561517f565b8280016001018555821561517f579182015b8281111561517f578251825591602001919060010190615164565b5061486a9291505b8082111561486a5760008155600101615187565b60005b838110156151b657818101518382015260200161519e565b8381111561164b5750506000910152565b60208152600082518060208401526151e681604085016020870161519b565b601f01601f19169190910160400192915050565b60006020828403121561520c57600080fd5b5035919050565b6001600160a01b0381168114610dac57600080fd5b6000806040838503121561523b57600080fd5b823561524681615213565b946020939093013593505050565b600080600083850361012081121561526b57600080fd5b6101008082121561527b57600080fd5b859450840135905067ffffffffffffffff8082111561529957600080fd5b818601915086601f8301126152ad57600080fd5b8135818111156152bc57600080fd5b87602060a0830285010111156152d157600080fd5b6020830194508093505050509250925092565b6000806000606084860312156152f957600080fd5b833561530481615213565b9250602084013561531481615213565b929592945050506040919091013590565b60006020828403121561533757600080fd5b813561167081615213565b6000806040838503121561535557600080fd5b82359150602083013561536781615213565b809150509250929050565b6000806040838503121561538557600080fd5b50508035926020909101359150565b63ffffffff81168114610dac57600080fd5b803561ffff81168114613de357600080fd5b600080600080600080600080610100898b0312156153d557600080fd5b88356153e081615213565b9750602089013596506040890135955060608901359450608089013561540581615213565b935060a0890135925060c089013561541c81615394565b915061542a60e08a016153a6565b90509295985092959890939650565b6000806000806080858703121561544f57600080fd5b84359350602085013561546181615213565b93969395505050506040820135916060013590565b60008060006060848603121561548b57600080fd5b83359250602084013561549d81615213565b915060408401356154ad81615213565b809150509250925092565b634e487b7160e01b600052602160045260246000fd5b60208101600883106154f057634e487b7160e01b600052602160045260246000fd5b91905290565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff8111828210171561552f5761552f6154f6565b60405290565b604051601f8201601f1916810167ffffffffffffffff8111828210171561555e5761555e6154f6565b604052919050565b8015158114610dac57600080fd5b6000602080838503121561558757600080fd5b823567ffffffffffffffff8082111561559f57600080fd5b818501915085601f8301126155b357600080fd5b8135818111156155c5576155c56154f6565b6155d3848260051b01615535565b818152848101925060a09182028401850191888311156155f257600080fd5b938501935b8285101561566b5780858a03121561560f5760008081fd5b61561761550c565b853561562281615213565b81528587013561563181615566565b8188015260408681013561564481615394565b908201526060868101359082015260808087013590820152845293840193928501926155f7565b50979650505050505050565b6000806040838503121561568a57600080fd5b823561569581615213565b9150602083013561536781615213565b6000602082840312156156b757600080fd5b815161167081615213565b6000602082840312156156d457600080fd5b815161167081615566565b60208082526002908201526104f560f41b604082015260600190565b6020808252600190820152600560fc1b604082015260600190565b600181811c9082168061572a57607f821691505b6020821081141561574b57634e487b7160e01b600052602260045260246000fd5b50919050565b60006020828403121561576357600080fd5b813561167081615394565b60006020828403121561578057600080fd5b611670826153a6565b634e487b7160e01b600052603260045260246000fd5b81356157aa81615213565b81546001600160a01b031981166001600160a01b0392909216918217835560208401356157d681615566565b60ff60a01b90151560a01b166001600160a81b03198216831781178455604085013561580181615394565b6001600160c81b0319929092169092179190911760a89190911b63ffffffff60a81b1617815560608201356001820155608090910135600290910155565b634e487b7160e01b600052601160045260246000fd5b60006000198214156158695761586961583f565b5060010190565b600082198211156158835761588361583f565b500190565b60006020808301818452808554808352604092508286019150866000528360002060005b828110156159045781546001600160a01b038116855260a081811c60ff1615158887015260a89190911c63ffffffff1686860152600180840154606087015260028401546080870152940193600390920191016158ac565b5091979650505050505050565b60006020828403121561592357600080fd5b5051919050565b60208082526005908201526405343465f560dc1b604082015260600190565b60208082526014908201527313dc9858db194e88139bdd08105c1c1c9bdd995960621b604082015260600190565b60008160001904831182151516156159915761599161583f565b500290565b634e487b7160e01b600052601260045260246000fd5b6000826159bb576159bb615996565b500490565b6000828210156159d2576159d261583f565b500390565b600080821280156001600160ff1b03849003851316156159f9576159f961583f565b600160ff1b8390038412811615615a1257615a1261583f565b50500190565b60008083128015600160ff1b850184121615615a3657615a3661583f565b6001600160ff1b0384018313811615615a5157615a5161583f565b50500390565b600061ffff83811690831681811015615a7257615a7261583f565b039392505050565b600061ffff808316818516808303821115615a9757615a9761583f565b01949350505050565b602080825282518282018190526000919060409081850190868401855b8281101561590457815180516001600160a01b03168552868101511515878601528581015163ffffffff1686860152606080820151908601526080908101519085015260a09093019290850190600101615abd565b60006001600160ff1b0381841382841380821686840486111615615b3857615b3861583f565b600160ff1b6000871282811687830589121615615b5757615b5761583f565b60008712925087820587128484161615615b7357615b7361583f565b87850587128184161615615b8957615b8961583f565b505050929093029392505050565b600082615ba657615ba6615996565b600160ff1b821460001984141615615bc057615bc061583f565b500590565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b600060208284031215615c2257600080fd5b815167ffffffffffffffff80821115615c3a57600080fd5b818401915084601f830112615c4e57600080fd5b815181811115615c6057615c606154f6565b615c73601f8201601f1916602001615535565b9150808252856020828501011115615c8a57600080fd5b615c9b81602084016020860161519b565b50949350505050565b60008351615cb681846020880161519b565b602d60f81b9083019081528351615cd481600184016020880161519b565b662073686172657360c81b60019290910191820152600801949350505050565b60008351615d0681846020880161519b565b602d60f81b9083019081528351615d2481600184016020880161519b565b01600101949350505050565b600080600080600080600080610100898b031215615d4d57600080fd5b8851615d5881615213565b60208a0151909850615d6981615213565b60408a015160608b01519198509650615d8181615213565b60808a015160a08b01519196509450615d9981615394565b60c08a0151909350615daa81615394565b60e08a015190925060078110615dbf57600080fd5b809150509295985092959890939650565b600060408284031215615de257600080fd5b6040516040810181811067ffffffffffffffff82111715615e0557615e056154f6565b604052825181526020928301519281019290925250919050565b6000600160ff1b821415615e3557615e3561583f565b5060000390565b600080600060608486031215615e5157600080fd5b8351925060208401519150604084015190509250925092565b600181815b80851115615ea5578160001904821115615e8b57615e8b61583f565b80851615615e9857918102915b93841c9390800290615e6f565b509250929050565b600082615ebc57506001610e54565b81615ec957506000610e54565b8160018114615edf5760028114615ee957615f05565b6001915050610e54565b60ff841115615efa57615efa61583f565b50506001821b610e54565b5060208310610133831016604e8410600b8410161715615f28575081810a610e54565b615f328383615e6a565b8060001904821115615f4657615f4661583f565b029392505050565b60006116708383615ead565b60008251615f6c81846020870161519b565b919091019291505056fea26469706673582212205dd074caf08c3376323c04f8f0d2ea3c433bdabbb0d3296aae3ab84d9cc5ddf764736f6c634300080b0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb282290000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb000000000000000000000000203e8740894c8955cb8950759876d7e7e45e04c1
-----Decoded View---------------
Arg [0] : _tellerV2 (address): 0xf7B14778035fEAF44540A0bC1D4ED859bCB28229
Arg [1] : _smartCommitmentForwarder (address): 0x9Fa5A22A3c0b8030147d363f68A763DEB9f00acB
Arg [2] : _uniswapV3Factory (address): 0x203e8740894c8955cB8950759876d7E7E45E04c1
-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 000000000000000000000000f7b14778035feaf44540a0bc1d4ed859bcb28229
Arg [1] : 0000000000000000000000009fa5a22a3c0b8030147d363f68a763deb9f00acb
Arg [2] : 000000000000000000000000203e8740894c8955cb8950759876d7e7e45e04c1
Loading...
Loading
Loading...
Loading

Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.