MON Price: $0.020567 (+9.42%)

Contract

0x0904B276a467CfCBD7B2F900aDaAAD783AEeC98F

Overview

MON Balance

Monad Chain LogoMonad Chain LogoMonad Chain Logo0 MON

MON Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

> 10 Internal Transactions found.

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
514345552026-01-27 10:30:322 hrs ago1769509832
0x0904B276...83AEeC98F
0 MON
514195872026-01-27 8:50:454 hrs ago1769503845
0x0904B276...83AEeC98F
0 MON
514048602026-01-27 7:12:325 hrs ago1769497952
0x0904B276...83AEeC98F
0 MON
513651962026-01-27 2:47:4410 hrs ago1769482064
0x0904B276...83AEeC98F
0 MON
513566272026-01-27 1:50:3711 hrs ago1769478637
0x0904B276...83AEeC98F
0 MON
513356392026-01-26 23:30:4613 hrs ago1769470246
0x0904B276...83AEeC98F
0 MON
512757392026-01-26 16:51:3720 hrs ago1769446297
0x0904B276...83AEeC98F
0 MON
512655802026-01-26 15:43:5121 hrs ago1769442231
0x0904B276...83AEeC98F
0 MON
512433832026-01-26 13:15:4623 hrs ago1769433346
0x0904B276...83AEeC98F
0 MON
511286062026-01-26 0:30:5236 hrs ago1769387452
0x0904B276...83AEeC98F
0 MON
511222782026-01-25 23:48:3937 hrs ago1769384919
0x0904B276...83AEeC98F
0 MON
510444402026-01-25 15:09:0345 hrs ago1769353743
0x0904B276...83AEeC98F
0 MON
510436152026-01-25 15:03:3345 hrs ago1769353413
0x0904B276...83AEeC98F
0 MON
510232922026-01-25 12:47:512 days ago1769345271
0x0904B276...83AEeC98F
0 MON
510117532026-01-25 11:30:492 days ago1769340649
0x0904B276...83AEeC98F
0 MON
510056132026-01-25 10:49:502 days ago1769338190
0x0904B276...83AEeC98F
0 MON
509418522026-01-25 3:43:442 days ago1769312624
0x0904B276...83AEeC98F
0 MON
509339652026-01-25 2:51:052 days ago1769309465
0x0904B276...83AEeC98F
0 MON
508695422026-01-24 19:41:382 days ago1769283698
0x0904B276...83AEeC98F
0 MON
507641692026-01-24 7:58:063 days ago1769241486
0x0904B276...83AEeC98F
0 MON
507592452026-01-24 7:25:133 days ago1769239513
0x0904B276...83AEeC98F
0 MON
506985982026-01-24 0:40:583 days ago1769215258
0x0904B276...83AEeC98F
0 MON
506457292026-01-23 18:47:593 days ago1769194079
0x0904B276...83AEeC98F
0 MON
506276572026-01-23 16:47:143 days ago1769186834
0x0904B276...83AEeC98F
0 MON
506257092026-01-23 16:34:143 days ago1769186054
0x0904B276...83AEeC98F
0 MON
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
UserVault

Compiler Version
v0.8.30+commit.73712a01

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IAaveOracle} from "@aave/core-v3/contracts/interfaces/IAaveOracle.sol";
import {IPoolAddressesProviderRegistry} from "@aave/core-v3/contracts/interfaces/IPoolAddressesProviderRegistry.sol";
import {IPoolAddressesProvider} from "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol";
import {IPool} from "@aave/core-v3/contracts/interfaces/IPool.sol";

import {IRevenueReward} from "../interfaces/IRevenueReward.sol";
import {IUserVaultRegistry} from "../interfaces/IUserVaultRegistry.sol";
import {IUserVault} from "../interfaces/IUserVault.sol";

import {CommonChecksLibrary} from "../libraries/CommonChecksLibrary.sol";

/**
 * @title UserVault
 * @author Neverland
 * @notice User vault contract for self-repaying loans
 */
contract UserVault is IUserVault, Initializable {
    using SafeERC20 for IERC20;

    /// @notice UserVaultRegistry contract
    IUserVaultRegistry public userVaultRegistry;
    /// @notice RevenueReward contract
    IRevenueReward public revenueReward;
    /// @notice AAVE PoolAddressesProviderRegistry contract
    IPoolAddressesProviderRegistry public poolAddressesProviderRegistry;

    /// @notice User address
    address public user;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initializes the contract
     * @param _user User address
     * @param _revenueReward RevenueReward address
     * @param _userVaultRegistry UserVaultRegistry address
     * @param _poolAddressesProviderRegistry PoolAddressesProviderRegistry address
     */
    function initialize(
        address _user,
        IRevenueReward _revenueReward,
        IUserVaultRegistry _userVaultRegistry,
        IPoolAddressesProviderRegistry _poolAddressesProviderRegistry
    ) external initializer {
        CommonChecksLibrary.revertIfZeroAddress(address(_userVaultRegistry));
        CommonChecksLibrary.revertIfZeroAddress(address(_poolAddressesProviderRegistry));
        CommonChecksLibrary.revertIfZeroAddress(address(_revenueReward));
        CommonChecksLibrary.revertIfZeroAddress(_user);

        user = _user;
        revenueReward = _revenueReward;
        userVaultRegistry = _userVaultRegistry;
        poolAddressesProviderRegistry = _poolAddressesProviderRegistry;
    }

    /// @inheritdoc IUserVault
    function repayUserDebt(RepayUserDebtParams calldata params) external onlyExecutor {
        getTokenIdsReward(params.tokenIds, params.rewardToken);

        uint256 debtTokenSwapAmount = swapAndVerify(
            params.rewardToken,
            params.rewardTokenAmountToSwap,
            params.debtToken,
            params.aggregatorAddress,
            params.aggregatorData,
            params.poolAddressesProvider,
            params.maxSlippageBps
        );

        repayDebt(params.poolAddressesProvider, params.debtToken, debtTokenSwapAmount);
    }

    /// @inheritdoc IUserVault
    function getTokenIdsReward(uint256[] memory tokenIds, address rewardToken) public onlyExecutor returns (uint256) {
        CommonChecksLibrary.revertIfZeroAddress(rewardToken);

        uint256 rewardTokenTokenBalanceBefore = _getErc20TokenBalance(rewardToken, address(this));

        address[] memory rewardTokens = new address[](1);
        rewardTokens[0] = address(rewardToken);
        uint256 tokenIdsLength = tokenIds.length;
        for (uint256 i = 0; i < tokenIdsLength; ++i) {
            if (revenueReward.tokenRewardReceiver(tokenIds[i]) != address(this)) {
                revert InvalidUserVaultForToken();
            }
            revenueReward.getReward(tokenIds[i], rewardTokens);
        }

        uint256 rewardTokenTokenBalanceAfter = _getErc20TokenBalance(rewardToken, address(this));
        uint256 rewardTokenAmount = rewardTokenTokenBalanceAfter - rewardTokenTokenBalanceBefore;
        return rewardTokenAmount;
    }

    /// @inheritdoc IUserVault
    function swapAndVerify(
        address tokenIn,
        uint256 tokenInAmount,
        address tokenOut,
        address aggregator,
        bytes memory aggregatorData,
        address poolAddressesProvider,
        uint256 maxAllowedSlippageBps
    ) public onlyExecutor poolAddressesProviderShouldBeValid(poolAddressesProvider) returns (uint256) {
        CommonChecksLibrary.revertIfZeroAddress(tokenIn);
        CommonChecksLibrary.revertIfZeroAddress(tokenOut);
        CommonChecksLibrary.revertIfZeroAmount(tokenInAmount);
        CommonChecksLibrary.revertIfZeroAddress(aggregator);
        if (maxAllowedSlippageBps > userVaultRegistry.maxSwapSlippageBps()) revert MaxSlippageTooHigh();

        uint256 debtTokenSwapAmount = _swap(tokenIn, tokenInAmount, tokenOut, aggregator, aggregatorData);

        uint256[] memory tokenPricesInUSD_8dec =
            _getTokenPricesInUsd_8dec(tokenIn, tokenOut, IPoolAddressesProvider(poolAddressesProvider));

        // Ensure oracle returned valid non-zero prices for both tokens
        if (tokenPricesInUSD_8dec.length < 2 || tokenPricesInUSD_8dec[0] == 0 || tokenPricesInUSD_8dec[1] == 0) {
            revert GettingAssetPriceFailed();
        }

        _verifySlippage(
            tokenIn,
            tokenInAmount,
            tokenPricesInUSD_8dec[0],
            tokenOut,
            debtTokenSwapAmount,
            tokenPricesInUSD_8dec[1],
            maxAllowedSlippageBps
        );

        return debtTokenSwapAmount;
    }

    /// @inheritdoc IUserVault
    function repayDebt(address poolAddressesProvider, address debtToken, uint256 amount)
        public
        onlyExecutor
        poolAddressesProviderShouldBeValid(poolAddressesProvider)
    {
        address poolAddress = IPoolAddressesProvider(poolAddressesProvider).getPool();
        IERC20(debtToken).safeApprove(poolAddress, amount);
        IPool(poolAddress).repay(debtToken, amount, 2, user);
        IERC20(debtToken).safeApprove(poolAddress, 0);

        emit LoanSelfRepaid(user, address(this), poolAddressesProvider, debtToken, amount);
    }

    /// @inheritdoc IUserVault
    function depositCollateral(address poolAddressesProvider, address debtToken, uint256 amount)
        external
        onlyExecutor
        poolAddressesProviderShouldBeValid(poolAddressesProvider)
    {
        address poolAddress = IPoolAddressesProvider(poolAddressesProvider).getPool();
        IERC20(debtToken).safeApprove(poolAddress, amount);
        IPool(poolAddress).supply(debtToken, amount, user, 0);
        IERC20(debtToken).safeApprove(poolAddress, 0);
    }

    /// @inheritdoc IUserVault
    function recoverERC20(address token, uint256 amount) external onlyExecutorOrUser {
        IERC20(token).safeTransfer(user, amount);
    }

    /// @inheritdoc IUserVault
    function recoverETH(uint256 amount) external onlyExecutorOrUser {
        (bool ok,) = payable(user).call{value: amount}("");
        if (!ok) revert IUserVault.ETHSendFailed();
    }

    /*//////////////////////////////////////////////////////////////
                            HELPERS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Swaps a specified token using a given aggregator contract.
     * @param tokenIn The address of the token swapped in.
     * @param tokenInAmount Amount needed to swap tokens.
     * @param tokenOut The address of the token swapped out.
     * @param aggregator The address of the swap aggregator contract to use for performing the swap.
     * @param aggregatorData The calldata required by the aggregator contract for the swap execution.
     * @return Amount of tokens swapped out
     */
    function _swap(
        address tokenIn,
        uint256 tokenInAmount,
        address tokenOut,
        address aggregator,
        bytes memory aggregatorData
    ) internal returns (uint256) {
        uint256 debtTokenBalanceBefore = _getErc20TokenBalance(tokenOut, address(this));

        if (!userVaultRegistry.isSupportedAggregator(aggregator)) {
            revert AggregatorNotSupported();
        }
        IERC20(tokenIn).safeApprove(aggregator, tokenInAmount);

        (bool success,) = aggregator.call(aggregatorData);
        if (!success) revert SwapFailed();

        uint256 debtTokenBalanceAfter = _getErc20TokenBalance(tokenOut, address(this));
        uint256 debtTokenSwapAmount = debtTokenBalanceAfter - debtTokenBalanceBefore;

        IERC20(tokenIn).safeApprove(aggregator, 0);

        return debtTokenSwapAmount;
    }

    /**
     * @notice Returns a list of prices from a list of assets addresses
     * @param token1 token1 address
     * @param token2 token2 address
     * @return The prices of the given assets
     */
    function _getTokenPricesInUsd_8dec(address token1, address token2, IPoolAddressesProvider poolAddressesProvider)
        internal
        view
        returns (uint256[] memory)
    {
        address[] memory tokens = new address[](2);
        tokens[0] = token1;
        tokens[1] = token2;

        return IAaveOracle(poolAddressesProvider.getPriceOracle()).getAssetsPrices(tokens);
    }

    /**
     * @notice Gets the balance of an ERC20 token for a specified account
     * @param erc20Token The address of the ERC20 token
     * @param account The address of the account to check balance for
     * @return The balance of the ERC20 token for the specified account
     */
    function _getErc20TokenBalance(address erc20Token, address account) internal view returns (uint256) {
        return IERC20(erc20Token).balanceOf(account);
    }

    /*//////////////////////////////////////////////////////////////
                            CALCULATIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Verifies that the slippage between the desired swap amount and the actual swapped amount is within the allowed slippage
     * @dev Normalizes token amounts to 18 decimals before comparison to handle tokens with different decimals
     * @param tokenA The address of token A (token being swapped from)
     * @param desiredSwapAmountInTokenA The desired amount of token A to swap
     * @param tokenAUnitPriceInUSD_8dec The price of token A in USD with 8 decimals
     * @param tokenB The address of token B (token being swapped to)
     * @param actualSwappedAmountInTokenB The actual amount of token B that was swapped
     * @param tokenBUnitPriceInUSD_8dec The price of token B in USD with 8 decimals
     * @param maxAllowedSlippageBps The maximum allowed slippage in basis points
     */
    function _verifySlippage(
        address tokenA,
        uint256 desiredSwapAmountInTokenA,
        uint256 tokenAUnitPriceInUSD_8dec,
        address tokenB,
        uint256 actualSwappedAmountInTokenB,
        uint256 tokenBUnitPriceInUSD_8dec,
        uint256 maxAllowedSlippageBps
    ) internal view {
        // Get token decimals
        uint8 tokenADecimals = IERC20Metadata(tokenA).decimals();
        uint8 tokenBDecimals = IERC20Metadata(tokenB).decimals();

        uint256 desiredSwapAmountInUsd = desiredSwapAmountInTokenA * tokenAUnitPriceInUSD_8dec / 10 ** tokenADecimals;
        uint256 actualSwapAmountInUsd = actualSwappedAmountInTokenB * tokenBUnitPriceInUSD_8dec / 10 ** tokenBDecimals;

        if (actualSwapAmountInUsd < desiredSwapAmountInUsd) {
            uint256 actualSlippageBps =
                (desiredSwapAmountInUsd - actualSwapAmountInUsd) * 10_000 / desiredSwapAmountInUsd;

            if (actualSlippageBps > maxAllowedSlippageBps) revert SlippageExceeded();
        }
    }

    /*//////////////////////////////////////////////////////////////
                             MODIFIERS
     //////////////////////////////////////////////////////////////*/

    /// @notice Modifier to check if the caller is the executor
    modifier onlyExecutor() {
        if (userVaultRegistry.executor() != msg.sender) {
            revert NotExecutor();
        }
        _;
    }

    /// @notice Modifier to check if the caller is the executor or the user
    modifier onlyExecutorOrUser() {
        if (!(userVaultRegistry.executor() == msg.sender || user == msg.sender)) {
            revert CommonChecksLibrary.UnauthorizedAccess();
        }
        _;
    }

    /// @notice Modifier to check if the pool addresses provider is valid
    modifier poolAddressesProviderShouldBeValid(address poolAddressesProvider) {
        uint256 poolAddressesProviderId =
            poolAddressesProviderRegistry.getAddressesProviderIdByAddress(poolAddressesProvider);
        if (poolAddressesProviderId == 0) revert InvalidPoolAddressesProvider();
        _;
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {IPriceOracleGetter} from './IPriceOracleGetter.sol';
import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';

/**
 * @title IAaveOracle
 * @author Aave
 * @notice Defines the basic interface for the Aave Oracle
 */
interface IAaveOracle is IPriceOracleGetter {
  /**
   * @dev Emitted after the base currency is set
   * @param baseCurrency The base currency of used for price quotes
   * @param baseCurrencyUnit The unit of the base currency
   */
  event BaseCurrencySet(address indexed baseCurrency, uint256 baseCurrencyUnit);

  /**
   * @dev Emitted after the price source of an asset is updated
   * @param asset The address of the asset
   * @param source The price source of the asset
   */
  event AssetSourceUpdated(address indexed asset, address indexed source);

  /**
   * @dev Emitted after the address of fallback oracle is updated
   * @param fallbackOracle The address of the fallback oracle
   */
  event FallbackOracleUpdated(address indexed fallbackOracle);

  /**
   * @notice Returns the PoolAddressesProvider
   * @return The address of the PoolAddressesProvider contract
   */
  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);

  /**
   * @notice Sets or replaces price sources of assets
   * @param assets The addresses of the assets
   * @param sources The addresses of the price sources
   */
  function setAssetSources(address[] calldata assets, address[] calldata sources) external;

  /**
   * @notice Sets the fallback oracle
   * @param fallbackOracle The address of the fallback oracle
   */
  function setFallbackOracle(address fallbackOracle) external;

  /**
   * @notice Returns a list of prices from a list of assets addresses
   * @param assets The list of assets addresses
   * @return The prices of the given assets
   */
  function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory);

  /**
   * @notice Returns the address of the source for an asset address
   * @param asset The address of the asset
   * @return The address of the source
   */
  function getSourceOfAsset(address asset) external view returns (address);

  /**
   * @notice Returns the address of the fallback oracle
   * @return The address of the fallback oracle
   */
  function getFallbackOracle() external view returns (address);
}

File 3 of 26 : IPool.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';

/**
 * @title IPool
 * @author Aave
 * @notice Defines the basic interface for an Aave Pool.
 */
interface IPool {
  /**
   * @dev Emitted on mintUnbacked()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address initiating the supply
   * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens
   * @param amount The amount of supplied assets
   * @param referralCode The referral code used
   */
  event MintUnbacked(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on backUnbacked()
   * @param reserve The address of the underlying asset of the reserve
   * @param backer The address paying for the backing
   * @param amount The amount added as backing
   * @param fee The amount paid in fees
   */
  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);

  /**
   * @dev Emitted on supply()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address initiating the supply
   * @param onBehalfOf The beneficiary of the supply, receiving the aTokens
   * @param amount The amount supplied
   * @param referralCode The referral code used
   */
  event Supply(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on withdraw()
   * @param reserve The address of the underlying asset being withdrawn
   * @param user The address initiating the withdrawal, owner of aTokens
   * @param to The address that will receive the underlying
   * @param amount The amount to be withdrawn
   */
  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);

  /**
   * @dev Emitted on borrow() and flashLoan() when debt needs to be opened
   * @param reserve The address of the underlying asset being borrowed
   * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
   * initiator of the transaction on flashLoan()
   * @param onBehalfOf The address that will be getting the debt
   * @param amount The amount borrowed out
   * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable
   * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray
   * @param referralCode The referral code used
   */
  event Borrow(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    DataTypes.InterestRateMode interestRateMode,
    uint256 borrowRate,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on repay()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The beneficiary of the repayment, getting his debt reduced
   * @param repayer The address of the user initiating the repay(), providing the funds
   * @param amount The amount repaid
   * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly
   */
  event Repay(
    address indexed reserve,
    address indexed user,
    address indexed repayer,
    uint256 amount,
    bool useATokens
  );

  /**
   * @dev Emitted on swapBorrowRateMode()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user swapping his rate mode
   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable
   */
  event SwapBorrowRateMode(
    address indexed reserve,
    address indexed user,
    DataTypes.InterestRateMode interestRateMode
  );

  /**
   * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets
   * @param asset The address of the underlying asset of the reserve
   * @param totalDebt The total isolation mode debt for the reserve
   */
  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);

  /**
   * @dev Emitted when the user selects a certain asset category for eMode
   * @param user The address of the user
   * @param categoryId The category id
   */
  event UserEModeSet(address indexed user, uint8 categoryId);

  /**
   * @dev Emitted on setUserUseReserveAsCollateral()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user enabling the usage as collateral
   */
  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on setUserUseReserveAsCollateral()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user enabling the usage as collateral
   */
  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on rebalanceStableBorrowRate()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user for which the rebalance has been executed
   */
  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on flashLoan()
   * @param target The address of the flash loan receiver contract
   * @param initiator The address initiating the flash loan
   * @param asset The address of the asset being flash borrowed
   * @param amount The amount flash borrowed
   * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt
   * @param premium The fee flash borrowed
   * @param referralCode The referral code used
   */
  event FlashLoan(
    address indexed target,
    address initiator,
    address indexed asset,
    uint256 amount,
    DataTypes.InterestRateMode interestRateMode,
    uint256 premium,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted when a borrower is liquidated.
   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
   * @param user The address of the borrower getting liquidated
   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
   * @param liquidatedCollateralAmount The amount of collateral received by the liquidator
   * @param liquidator The address of the liquidator
   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
   * to receive the underlying collateral asset directly
   */
  event LiquidationCall(
    address indexed collateralAsset,
    address indexed debtAsset,
    address indexed user,
    uint256 debtToCover,
    uint256 liquidatedCollateralAmount,
    address liquidator,
    bool receiveAToken
  );

  /**
   * @dev Emitted when the state of a reserve is updated.
   * @param reserve The address of the underlying asset of the reserve
   * @param liquidityRate The next liquidity rate
   * @param stableBorrowRate The next stable borrow rate
   * @param variableBorrowRate The next variable borrow rate
   * @param liquidityIndex The next liquidity index
   * @param variableBorrowIndex The next variable borrow index
   */
  event ReserveDataUpdated(
    address indexed reserve,
    uint256 liquidityRate,
    uint256 stableBorrowRate,
    uint256 variableBorrowRate,
    uint256 liquidityIndex,
    uint256 variableBorrowIndex
  );

  /**
   * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.
   * @param reserve The address of the reserve
   * @param amountMinted The amount minted to the treasury
   */
  event MintedToTreasury(address indexed reserve, uint256 amountMinted);

  /**
   * @notice Mints an `amount` of aTokens to the `onBehalfOf`
   * @param asset The address of the underlying asset to mint
   * @param amount The amount to mint
   * @param onBehalfOf The address that will receive the aTokens
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function mintUnbacked(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode
  ) external;

  /**
   * @notice Back the current unbacked underlying with `amount` and pay `fee`.
   * @param asset The address of the underlying asset to back
   * @param amount The amount to back
   * @param fee The amount paid in fees
   * @return The backed amount
   */
  function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256);

  /**
   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

  /**
   * @notice Supply with transfer approval of asset to be supplied done via permit function
   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param deadline The deadline timestamp that the permit is valid
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   * @param permitV The V parameter of ERC712 permit sig
   * @param permitR The R parameter of ERC712 permit sig
   * @param permitS The S parameter of ERC712 permit sig
   */
  function supplyWithPermit(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external;

  /**
   * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
   * @param asset The address of the underlying asset to withdraw
   * @param amount The underlying amount to be withdrawn
   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance
   * @param to The address that will receive the underlying, same as msg.sender if the user
   *   wants to receive it on his own wallet, or a different address if the beneficiary is a
   *   different wallet
   * @return The final amount withdrawn
   */
  function withdraw(address asset, uint256 amount, address to) external returns (uint256);

  /**
   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the
   * corresponding debt token (StableDebtToken or VariableDebtToken)
   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`
   * @param asset The address of the underlying asset to borrow
   * @param amount The amount to be borrowed
   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself
   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
   * if he has been given credit delegation allowance
   */
  function borrow(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode,
    address onBehalfOf
  ) external;

  /**
   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
   * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the
   * user calling the function if he wants to reduce/remove his own debt, or the address of any other
   * other borrower whose debt should be removed
   * @return The final amount repaid
   */
  function repay(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf
  ) external returns (uint256);

  /**
   * @notice Repay with transfer approval of asset to be repaid done via permit function
   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
   * user calling the function if he wants to reduce/remove his own debt, or the address of any other
   * other borrower whose debt should be removed
   * @param deadline The deadline timestamp that the permit is valid
   * @param permitV The V parameter of ERC712 permit sig
   * @param permitR The R parameter of ERC712 permit sig
   * @param permitS The S parameter of ERC712 permit sig
   * @return The final amount repaid
   */
  function repayWithPermit(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external returns (uint256);

  /**
   * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the
   * equivalent debt tokens
   * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens
   * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken
   * balance is not enough to cover the whole debt
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @return The final amount repaid
   */
  function repayWithATokens(
    address asset,
    uint256 amount,
    uint256 interestRateMode
  ) external returns (uint256);

  /**
   * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa
   * @param asset The address of the underlying asset borrowed
   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable
   */
  function swapBorrowRateMode(address asset, uint256 interestRateMode) external;

  /**
   * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
   * - Users can be rebalanced if the following conditions are satisfied:
   *     1. Usage ratio is above 95%
   *     2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too
   *        much has been borrowed at a stable rate and suppliers are not earning enough
   * @param asset The address of the underlying asset borrowed
   * @param user The address of the user to be rebalanced
   */
  function rebalanceStableBorrowRate(address asset, address user) external;

  /**
   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral
   * @param asset The address of the underlying asset supplied
   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise
   */
  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

  /**
   * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
   * @param user The address of the borrower getting liquidated
   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
   * to receive the underlying collateral asset directly
   */
  function liquidationCall(
    address collateralAsset,
    address debtAsset,
    address user,
    uint256 debtToCover,
    bool receiveAToken
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface
   * @param assets The addresses of the assets being flash-borrowed
   * @param amounts The amounts of the assets being flash-borrowed
   * @param interestRateModes Types of the debt to open if the flash loan is not returned:
   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function flashLoan(
    address receiverAddress,
    address[] calldata assets,
    uint256[] calldata amounts,
    uint256[] calldata interestRateModes,
    address onBehalfOf,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface
   * @param asset The address of the asset being flash-borrowed
   * @param amount The amount of the asset being flash-borrowed
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function flashLoanSimple(
    address receiverAddress,
    address asset,
    uint256 amount,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Returns the user account data across all the reserves
   * @param user The address of the user
   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed
   * @return totalDebtBase The total debt of the user in the base currency used by the price feed
   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed
   * @return currentLiquidationThreshold The liquidation threshold of the user
   * @return ltv The loan to value of The user
   * @return healthFactor The current health factor of the user
   */
  function getUserAccountData(
    address user
  )
    external
    view
    returns (
      uint256 totalCollateralBase,
      uint256 totalDebtBase,
      uint256 availableBorrowsBase,
      uint256 currentLiquidationThreshold,
      uint256 ltv,
      uint256 healthFactor
    );

  /**
   * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an
   * interest rate strategy
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param aTokenAddress The address of the aToken that will be assigned to the reserve
   * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve
   * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve
   * @param interestRateStrategyAddress The address of the interest rate strategy contract
   */
  function initReserve(
    address asset,
    address aTokenAddress,
    address stableDebtAddress,
    address variableDebtAddress,
    address interestRateStrategyAddress
  ) external;

  /**
   * @notice Drop a reserve
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   */
  function dropReserve(address asset) external;

  /**
   * @notice Updates the address of the interest rate strategy contract
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param rateStrategyAddress The address of the interest rate strategy contract
   */
  function setReserveInterestRateStrategyAddress(
    address asset,
    address rateStrategyAddress
  ) external;

  /**
   * @notice Sets the configuration bitmap of the reserve as a whole
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param configuration The new configuration bitmap
   */
  function setConfiguration(
    address asset,
    DataTypes.ReserveConfigurationMap calldata configuration
  ) external;

  /**
   * @notice Returns the configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The configuration of the reserve
   */
  function getConfiguration(
    address asset
  ) external view returns (DataTypes.ReserveConfigurationMap memory);

  /**
   * @notice Returns the configuration of the user across all the reserves
   * @param user The user address
   * @return The configuration of the user
   */
  function getUserConfiguration(
    address user
  ) external view returns (DataTypes.UserConfigurationMap memory);

  /**
   * @notice Returns the normalized income of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The reserve's normalized income
   */
  function getReserveNormalizedIncome(address asset) external view returns (uint256);

  /**
   * @notice Returns the normalized variable debt per unit of asset
   * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a
   * "dynamic" variable index based on time, current stored index and virtual rate at the current
   * moment (approx. a borrower would get if opening a position). This means that is always used in
   * combination with variable debt supply/balances.
   * If using this function externally, consider that is possible to have an increasing normalized
   * variable debt that is not equivalent to how the variable debt index would be updated in storage
   * (e.g. only updates with non-zero variable debt supply)
   * @param asset The address of the underlying asset of the reserve
   * @return The reserve normalized variable debt
   */
  function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);

  /**
   * @notice Returns the state and configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The state and configuration data of the reserve
   */
  function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);

  /**
   * @notice Validates and finalizes an aToken transfer
   * @dev Only callable by the overlying aToken of the `asset`
   * @param asset The address of the underlying asset of the aToken
   * @param from The user from which the aTokens are transferred
   * @param to The user receiving the aTokens
   * @param amount The amount being transferred/withdrawn
   * @param balanceFromBefore The aToken balance of the `from` user before the transfer
   * @param balanceToBefore The aToken balance of the `to` user before the transfer
   */
  function finalizeTransfer(
    address asset,
    address from,
    address to,
    uint256 amount,
    uint256 balanceFromBefore,
    uint256 balanceToBefore
  ) external;

  /**
   * @notice Returns the list of the underlying assets of all the initialized reserves
   * @dev It does not include dropped reserves
   * @return The addresses of the underlying assets of the initialized reserves
   */
  function getReservesList() external view returns (address[] memory);

  /**
   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct
   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct
   * @return The address of the reserve associated with id
   */
  function getReserveAddressById(uint16 id) external view returns (address);

  /**
   * @notice Returns the PoolAddressesProvider connected to this contract
   * @return The address of the PoolAddressesProvider
   */
  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);

  /**
   * @notice Updates the protocol fee on the bridging
   * @param bridgeProtocolFee The part of the premium sent to the protocol treasury
   */
  function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;

  /**
   * @notice Updates flash loan premiums. Flash loan premium consists of two parts:
   * - A part is sent to aToken holders as extra, one time accumulated interest
   * - A part is collected by the protocol treasury
   * @dev The total premium is calculated on the total borrowed amount
   * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`
   * @dev Only callable by the PoolConfigurator contract
   * @param flashLoanPremiumTotal The total premium, expressed in bps
   * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps
   */
  function updateFlashloanPremiums(
    uint128 flashLoanPremiumTotal,
    uint128 flashLoanPremiumToProtocol
  ) external;

  /**
   * @notice Configures a new category for the eMode.
   * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.
   * The category 0 is reserved as it's the default for volatile assets
   * @param id The id of the category
   * @param config The configuration of the category
   */
  function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory config) external;

  /**
   * @notice Returns the data of an eMode category
   * @param id The id of the category
   * @return The configuration data of the category
   */
  function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);

  /**
   * @notice Allows a user to use the protocol in eMode
   * @param categoryId The id of the category
   */
  function setUserEMode(uint8 categoryId) external;

  /**
   * @notice Returns the eMode the user is using
   * @param user The address of the user
   * @return The eMode id
   */
  function getUserEMode(address user) external view returns (uint256);

  /**
   * @notice Resets the isolation mode total debt of the given asset to zero
   * @dev It requires the given asset has zero debt ceiling
   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt
   */
  function resetIsolationModeTotalDebt(address asset) external;

  /**
   * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate
   * @return The percentage of available liquidity to borrow, expressed in bps
   */
  function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);

  /**
   * @notice Returns the total fee on flash loans
   * @return The total fee on flashloans
   */
  function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);

  /**
   * @notice Returns the part of the bridge fees sent to protocol
   * @return The bridge fee sent to the protocol treasury
   */
  function BRIDGE_PROTOCOL_FEE() external view returns (uint256);

  /**
   * @notice Returns the part of the flashloan fees sent to protocol
   * @return The flashloan fee sent to the protocol treasury
   */
  function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);

  /**
   * @notice Returns the maximum number of reserves supported to be listed in this Pool
   * @return The maximum number of reserves supported
   */
  function MAX_NUMBER_RESERVES() external view returns (uint16);

  /**
   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens
   * @param assets The list of reserves for which the minting needs to be executed
   */
  function mintToTreasury(address[] calldata assets) external;

  /**
   * @notice Rescue and transfer tokens locked in this contract
   * @param token The address of the token
   * @param to The address of the recipient
   * @param amount The amount of token to transfer
   */
  function rescueTokens(address token, address to, uint256 amount) external;

  /**
   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
   * @dev Deprecated: Use the `supply` function instead
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

/**
 * @title IPoolAddressesProvider
 * @author Aave
 * @notice Defines the basic interface for a Pool Addresses Provider.
 */
interface IPoolAddressesProvider {
  /**
   * @dev Emitted when the market identifier is updated.
   * @param oldMarketId The old id of the market
   * @param newMarketId The new id of the market
   */
  event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);

  /**
   * @dev Emitted when the pool is updated.
   * @param oldAddress The old address of the Pool
   * @param newAddress The new address of the Pool
   */
  event PoolUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the pool configurator is updated.
   * @param oldAddress The old address of the PoolConfigurator
   * @param newAddress The new address of the PoolConfigurator
   */
  event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the price oracle is updated.
   * @param oldAddress The old address of the PriceOracle
   * @param newAddress The new address of the PriceOracle
   */
  event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the ACL manager is updated.
   * @param oldAddress The old address of the ACLManager
   * @param newAddress The new address of the ACLManager
   */
  event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the ACL admin is updated.
   * @param oldAddress The old address of the ACLAdmin
   * @param newAddress The new address of the ACLAdmin
   */
  event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the price oracle sentinel is updated.
   * @param oldAddress The old address of the PriceOracleSentinel
   * @param newAddress The new address of the PriceOracleSentinel
   */
  event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the pool data provider is updated.
   * @param oldAddress The old address of the PoolDataProvider
   * @param newAddress The new address of the PoolDataProvider
   */
  event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when a new proxy is created.
   * @param id The identifier of the proxy
   * @param proxyAddress The address of the created proxy contract
   * @param implementationAddress The address of the implementation contract
   */
  event ProxyCreated(
    bytes32 indexed id,
    address indexed proxyAddress,
    address indexed implementationAddress
  );

  /**
   * @dev Emitted when a new non-proxied contract address is registered.
   * @param id The identifier of the contract
   * @param oldAddress The address of the old contract
   * @param newAddress The address of the new contract
   */
  event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the implementation of the proxy registered with id is updated
   * @param id The identifier of the contract
   * @param proxyAddress The address of the proxy contract
   * @param oldImplementationAddress The address of the old implementation contract
   * @param newImplementationAddress The address of the new implementation contract
   */
  event AddressSetAsProxy(
    bytes32 indexed id,
    address indexed proxyAddress,
    address oldImplementationAddress,
    address indexed newImplementationAddress
  );

  /**
   * @notice Returns the id of the Aave market to which this contract points to.
   * @return The market id
   */
  function getMarketId() external view returns (string memory);

  /**
   * @notice Associates an id with a specific PoolAddressesProvider.
   * @dev This can be used to create an onchain registry of PoolAddressesProviders to
   * identify and validate multiple Aave markets.
   * @param newMarketId The market id
   */
  function setMarketId(string calldata newMarketId) external;

  /**
   * @notice Returns an address by its identifier.
   * @dev The returned address might be an EOA or a contract, potentially proxied
   * @dev It returns ZERO if there is no registered address with the given id
   * @param id The id
   * @return The address of the registered for the specified id
   */
  function getAddress(bytes32 id) external view returns (address);

  /**
   * @notice General function to update the implementation of a proxy registered with
   * certain `id`. If there is no proxy registered, it will instantiate one and
   * set as implementation the `newImplementationAddress`.
   * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit
   * setter function, in order to avoid unexpected consequences
   * @param id The id
   * @param newImplementationAddress The address of the new implementation
   */
  function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;

  /**
   * @notice Sets an address for an id replacing the address saved in the addresses map.
   * @dev IMPORTANT Use this function carefully, as it will do a hard replacement
   * @param id The id
   * @param newAddress The address to set
   */
  function setAddress(bytes32 id, address newAddress) external;

  /**
   * @notice Returns the address of the Pool proxy.
   * @return The Pool proxy address
   */
  function getPool() external view returns (address);

  /**
   * @notice Updates the implementation of the Pool, or creates a proxy
   * setting the new `pool` implementation when the function is called for the first time.
   * @param newPoolImpl The new Pool implementation
   */
  function setPoolImpl(address newPoolImpl) external;

  /**
   * @notice Returns the address of the PoolConfigurator proxy.
   * @return The PoolConfigurator proxy address
   */
  function getPoolConfigurator() external view returns (address);

  /**
   * @notice Updates the implementation of the PoolConfigurator, or creates a proxy
   * setting the new `PoolConfigurator` implementation when the function is called for the first time.
   * @param newPoolConfiguratorImpl The new PoolConfigurator implementation
   */
  function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;

  /**
   * @notice Returns the address of the price oracle.
   * @return The address of the PriceOracle
   */
  function getPriceOracle() external view returns (address);

  /**
   * @notice Updates the address of the price oracle.
   * @param newPriceOracle The address of the new PriceOracle
   */
  function setPriceOracle(address newPriceOracle) external;

  /**
   * @notice Returns the address of the ACL manager.
   * @return The address of the ACLManager
   */
  function getACLManager() external view returns (address);

  /**
   * @notice Updates the address of the ACL manager.
   * @param newAclManager The address of the new ACLManager
   */
  function setACLManager(address newAclManager) external;

  /**
   * @notice Returns the address of the ACL admin.
   * @return The address of the ACL admin
   */
  function getACLAdmin() external view returns (address);

  /**
   * @notice Updates the address of the ACL admin.
   * @param newAclAdmin The address of the new ACL admin
   */
  function setACLAdmin(address newAclAdmin) external;

  /**
   * @notice Returns the address of the price oracle sentinel.
   * @return The address of the PriceOracleSentinel
   */
  function getPriceOracleSentinel() external view returns (address);

  /**
   * @notice Updates the address of the price oracle sentinel.
   * @param newPriceOracleSentinel The address of the new PriceOracleSentinel
   */
  function setPriceOracleSentinel(address newPriceOracleSentinel) external;

  /**
   * @notice Returns the address of the data provider.
   * @return The address of the DataProvider
   */
  function getPoolDataProvider() external view returns (address);

  /**
   * @notice Updates the address of the data provider.
   * @param newDataProvider The address of the new DataProvider
   */
  function setPoolDataProvider(address newDataProvider) external;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

/**
 * @title IPoolAddressesProviderRegistry
 * @author Aave
 * @notice Defines the basic interface for an Aave Pool Addresses Provider Registry.
 */
interface IPoolAddressesProviderRegistry {
  /**
   * @dev Emitted when a new AddressesProvider is registered.
   * @param addressesProvider The address of the registered PoolAddressesProvider
   * @param id The id of the registered PoolAddressesProvider
   */
  event AddressesProviderRegistered(address indexed addressesProvider, uint256 indexed id);

  /**
   * @dev Emitted when an AddressesProvider is unregistered.
   * @param addressesProvider The address of the unregistered PoolAddressesProvider
   * @param id The id of the unregistered PoolAddressesProvider
   */
  event AddressesProviderUnregistered(address indexed addressesProvider, uint256 indexed id);

  /**
   * @notice Returns the list of registered addresses providers
   * @return The list of addresses providers
   */
  function getAddressesProvidersList() external view returns (address[] memory);

  /**
   * @notice Returns the id of a registered PoolAddressesProvider
   * @param addressesProvider The address of the PoolAddressesProvider
   * @return The id of the PoolAddressesProvider or 0 if is not registered
   */
  function getAddressesProviderIdByAddress(
    address addressesProvider
  ) external view returns (uint256);

  /**
   * @notice Returns the address of a registered PoolAddressesProvider
   * @param id The id of the market
   * @return The address of the PoolAddressesProvider with the given id or zero address if it is not registered
   */
  function getAddressesProviderAddressById(uint256 id) external view returns (address);

  /**
   * @notice Registers an addresses provider
   * @dev The PoolAddressesProvider must not already be registered in the registry
   * @dev The id must not be used by an already registered PoolAddressesProvider
   * @param provider The address of the new PoolAddressesProvider
   * @param id The id for the new PoolAddressesProvider, referring to the market it belongs to
   */
  function registerAddressesProvider(address provider, uint256 id) external;

  /**
   * @notice Removes an addresses provider from the list of registered addresses providers
   * @param provider The PoolAddressesProvider address
   */
  function unregisterAddressesProvider(address provider) external;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

/**
 * @title IPriceOracleGetter
 * @author Aave
 * @notice Interface for the Aave price oracle.
 */
interface IPriceOracleGetter {
  /**
   * @notice Returns the base currency address
   * @dev Address 0x0 is reserved for USD as base currency.
   * @return Returns the base currency address.
   */
  function BASE_CURRENCY() external view returns (address);

  /**
   * @notice Returns the base currency unit
   * @dev 1 ether for ETH, 1e8 for USD.
   * @return Returns the base currency unit.
   */
  function BASE_CURRENCY_UNIT() external view returns (uint256);

  /**
   * @notice Returns the asset price in the base currency
   * @param asset The address of the asset
   * @return The price of the asset
   */
  function getAssetPrice(address asset) external view returns (uint256);
}

File 7 of 26 : DataTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

library DataTypes {
  struct ReserveData {
    //stores the reserve configuration
    ReserveConfigurationMap configuration;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    //the current supply rate. Expressed in ray
    uint128 currentLiquidityRate;
    //variable borrow index. Expressed in ray
    uint128 variableBorrowIndex;
    //the current variable borrow rate. Expressed in ray
    uint128 currentVariableBorrowRate;
    //the current stable borrow rate. Expressed in ray
    uint128 currentStableBorrowRate;
    //timestamp of last update
    uint40 lastUpdateTimestamp;
    //the id of the reserve. Represents the position in the list of the active reserves
    uint16 id;
    //aToken address
    address aTokenAddress;
    //stableDebtToken address
    address stableDebtTokenAddress;
    //variableDebtToken address
    address variableDebtTokenAddress;
    //address of the interest rate strategy
    address interestRateStrategyAddress;
    //the current treasury balance, scaled
    uint128 accruedToTreasury;
    //the outstanding unbacked aTokens minted through the bridging feature
    uint128 unbacked;
    //the outstanding debt borrowed against this asset in isolation mode
    uint128 isolationModeTotalDebt;
  }

  struct ReserveConfigurationMap {
    //bit 0-15: LTV
    //bit 16-31: Liq. threshold
    //bit 32-47: Liq. bonus
    //bit 48-55: Decimals
    //bit 56: reserve is active
    //bit 57: reserve is frozen
    //bit 58: borrowing is enabled
    //bit 59: stable rate borrowing enabled
    //bit 60: asset is paused
    //bit 61: borrowing in isolation mode is enabled
    //bit 62: siloed borrowing enabled
    //bit 63: flashloaning enabled
    //bit 64-79: reserve factor
    //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap
    //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap
    //bit 152-167 liquidation protocol fee
    //bit 168-175 eMode category
    //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
    //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
    //bit 252-255 unused

    uint256 data;
  }

  struct UserConfigurationMap {
    /**
     * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
     * The first bit indicates if an asset is used as collateral by the user, the second whether an
     * asset is borrowed by the user.
     */
    uint256 data;
  }

  struct EModeCategory {
    // each eMode category has a custom ltv and liquidation threshold
    uint16 ltv;
    uint16 liquidationThreshold;
    uint16 liquidationBonus;
    // each eMode category may or may not have a custom oracle to override the individual assets price oracles
    address priceSource;
    string label;
  }

  enum InterestRateMode {NONE, STABLE, VARIABLE}

  struct ReserveCache {
    uint256 currScaledVariableDebt;
    uint256 nextScaledVariableDebt;
    uint256 currPrincipalStableDebt;
    uint256 currAvgStableBorrowRate;
    uint256 currTotalStableDebt;
    uint256 nextAvgStableBorrowRate;
    uint256 nextTotalStableDebt;
    uint256 currLiquidityIndex;
    uint256 nextLiquidityIndex;
    uint256 currVariableBorrowIndex;
    uint256 nextVariableBorrowIndex;
    uint256 currLiquidityRate;
    uint256 currVariableBorrowRate;
    uint256 reserveFactor;
    ReserveConfigurationMap reserveConfiguration;
    address aTokenAddress;
    address stableDebtTokenAddress;
    address variableDebtTokenAddress;
    uint40 reserveLastUpdateTimestamp;
    uint40 stableDebtLastUpdateTimestamp;
  }

  struct ExecuteLiquidationCallParams {
    uint256 reservesCount;
    uint256 debtToCover;
    address collateralAsset;
    address debtAsset;
    address user;
    bool receiveAToken;
    address priceOracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
  }

  struct ExecuteSupplyParams {
    address asset;
    uint256 amount;
    address onBehalfOf;
    uint16 referralCode;
  }

  struct ExecuteBorrowParams {
    address asset;
    address user;
    address onBehalfOf;
    uint256 amount;
    InterestRateMode interestRateMode;
    uint16 referralCode;
    bool releaseUnderlying;
    uint256 maxStableRateBorrowSizePercent;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
  }

  struct ExecuteRepayParams {
    address asset;
    uint256 amount;
    InterestRateMode interestRateMode;
    address onBehalfOf;
    bool useATokens;
  }

  struct ExecuteWithdrawParams {
    address asset;
    uint256 amount;
    address to;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
  }

  struct ExecuteSetUserEModeParams {
    uint256 reservesCount;
    address oracle;
    uint8 categoryId;
  }

  struct FinalizeTransferParams {
    address asset;
    address from;
    address to;
    uint256 amount;
    uint256 balanceFromBefore;
    uint256 balanceToBefore;
    uint256 reservesCount;
    address oracle;
    uint8 fromEModeCategory;
  }

  struct FlashloanParams {
    address receiverAddress;
    address[] assets;
    uint256[] amounts;
    uint256[] interestRateModes;
    address onBehalfOf;
    bytes params;
    uint16 referralCode;
    uint256 flashLoanPremiumToProtocol;
    uint256 flashLoanPremiumTotal;
    uint256 maxStableRateBorrowSizePercent;
    uint256 reservesCount;
    address addressesProvider;
    uint8 userEModeCategory;
    bool isAuthorizedFlashBorrower;
  }

  struct FlashloanSimpleParams {
    address receiverAddress;
    address asset;
    uint256 amount;
    bytes params;
    uint16 referralCode;
    uint256 flashLoanPremiumToProtocol;
    uint256 flashLoanPremiumTotal;
  }

  struct FlashLoanRepaymentParams {
    uint256 amount;
    uint256 totalPremium;
    uint256 flashLoanPremiumToProtocol;
    address asset;
    address receiverAddress;
    uint16 referralCode;
  }

  struct CalculateUserAccountDataParams {
    UserConfigurationMap userConfig;
    uint256 reservesCount;
    address user;
    address oracle;
    uint8 userEModeCategory;
  }

  struct ValidateBorrowParams {
    ReserveCache reserveCache;
    UserConfigurationMap userConfig;
    address asset;
    address userAddress;
    uint256 amount;
    InterestRateMode interestRateMode;
    uint256 maxStableLoanPercent;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
    bool isolationModeActive;
    address isolationModeCollateralAddress;
    uint256 isolationModeDebtCeiling;
  }

  struct ValidateLiquidationCallParams {
    ReserveCache debtReserveCache;
    uint256 totalDebt;
    uint256 healthFactor;
    address priceOracleSentinel;
  }

  struct CalculateInterestRatesParams {
    uint256 unbacked;
    uint256 liquidityAdded;
    uint256 liquidityTaken;
    uint256 totalStableDebt;
    uint256 totalVariableDebt;
    uint256 averageStableBorrowRate;
    uint256 reserveFactor;
    address reserve;
    address aToken;
  }

  struct InitReserveParams {
    address asset;
    address aTokenAddress;
    address stableDebtAddress;
    address variableDebtAddress;
    address interestRateStrategyAddress;
    uint16 reservesCount;
    uint16 maxNumberReserves;
  }
}

File 8 of 26 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)

pragma solidity ^0.8.0;

import "../utils/introspection/IERC165.sol";

File 9 of 26 : IERC4906.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4906.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";
import "./IERC721.sol";

/// @title EIP-721 Metadata Update Extension
interface IERC4906 is IERC165, IERC721 {
    /// @dev This event emits when the metadata of a token is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFT.
    event MetadataUpdate(uint256 _tokenId);

    /// @dev This event emits when the metadata of a range of tokens is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFTs.
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC6372.sol)

pragma solidity ^0.8.0;

interface IERC6372 {
    /**
     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
     */
    function clock() external view returns (uint48);

    /**
     * @dev Description of the clock
     */
    // solhint-disable-next-line func-name-mixedcase
    function CLOCK_MODE() external view returns (string memory);
}

File 11 of 26 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol)

pragma solidity ^0.8.0;

import "../token/ERC721/IERC721.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.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]
 * ```solidity
 * 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) || (!Address.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 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.9.4) (token/ERC20/extensions/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.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
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].
     *
     * CAUTION: See Security Considerations above.
     */
    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 (last updated v4.9.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.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/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;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    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));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    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");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation 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).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // 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 cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @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.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/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.8.0/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/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 IERC165 {
    /**
     * @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);
}

File 21 of 26 : IDustLock.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

import {IERC4906} from "@openzeppelin/contracts/interfaces/IERC4906.sol";
import {IERC6372} from "@openzeppelin/contracts/interfaces/IERC6372.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

import {IRevenueReward} from "./IRevenueReward.sol";

/**
 * @title IDustLock Interface
 * @notice Interface for the DustLock contract that manages voting escrow NFTs (veNFTs)
 * @dev Combines ERC721 with vote-escrow functionality for governance and reward distribution
 */
interface IDustLock is IERC4906, IERC6372, IERC721Metadata {
    /**
     * @notice Structure representing a locked token position
     * @dev Used to track the amount of tokens locked, when they unlock, and if they're permanently locked
     * @param amount Amount of tokens locked in int256 format for consistency with precision calculations
     * @param effectiveStart Effective start time for penalty calculations (weighted average on lock operations)
     * @param end Timestamp when tokens unlock (0 for permanent locks)
     * @param isPermanent Whether this is a permanent lock that cannot be withdrawn normally
     */
    struct LockedBalance {
        int256 amount;
        uint256 effectiveStart;
        uint256 end;
        bool isPermanent;
    }

    /**
     * @notice Checkpoint for tracking user voting power at a specific point in time
     * @dev Used in the vote-escrow system to track decay of voting power over time
     * @param bias Voting power at time ts
     * @param slope Rate of voting power decrease per second (-dweight/dt)
     * @param ts Timestamp of the checkpoint
     * @param blk Block number at which the checkpoint was created
     * @param permanent Amount of permanent (non-decaying) voting power
     */
    struct UserPoint {
        int256 bias; // WAD format (18 decimals) for precision
        int256 slope; // WAD format (18 decimals) for precision # -dweight / dt
        uint256 ts;
        uint256 blk; // block
        uint256 permanent;
    }

    /**
     * @notice Global checkpoint for tracking total voting power at a specific point in time
     * @dev Similar to UserPoint but tracks system-wide totals
     * @param bias Total voting power at time ts
     * @param slope Total rate of voting power decrease per second (-dweight/dt)
     * @param ts Timestamp of the checkpoint
     * @param blk Block number at which the checkpoint was created
     * @param permanentLockBalance Total amount of permanently locked tokens
     */
    struct GlobalPoint {
        int256 bias; // WAD format (18 decimals) for precision
        int256 slope; // WAD format (18 decimals) for precision # -dweight / dt
        uint256 ts;
        uint256 blk; // block
        uint256 permanentLockBalance;
    }

    /**
     * @notice Types of deposit operations supported by the veNFT system
     * @param DEPOSIT_FOR_TYPE Adding tokens to an existing lock owned by someone else
     * @param CREATE_LOCK_TYPE Creating a new lock position
     * @param INCREASE_LOCK_AMOUNT Adding more tokens to an existing lock
     * @param INCREASE_UNLOCK_TIME Extending the lock duration of an existing lock
     */
    enum DepositType {
        DEPOSIT_FOR_TYPE,
        CREATE_LOCK_TYPE,
        INCREASE_LOCK_AMOUNT,
        INCREASE_UNLOCK_TIME
    }

    /// @notice Error thrown when the locked amount is less than minLockAmount
    error AmountTooSmall();

    /// @notice Error thrown when the requested amount exceeds available balance
    error AmountTooBig();

    /// @notice Error thrown when an ERC721 receiver contract rejects the tokens
    error ERC721ReceiverRejectedTokens();

    /// @notice Error thrown when transferring to an address that doesn't implement ERC721Receiver
    error ERC721TransferToNonERC721ReceiverImplementer();

    /// @notice Error thrown when an early withdraw penalty value is invalid (>=10000)
    error InvalidWithdrawPenalty();

    /// @notice Error thrown when the lock duration doesn't extend beyond the current time
    error LockDurationNotInFuture();

    /// @notice Error thrown when the lock duration exceeds the maximum allowed time
    error LockDurationTooLong();

    /// @notice Error thrown when the lock duration is less than the minimum required time
    error LockDurationTooShort();

    /// @notice Error thrown when trying to depositFor to a lock expiring within MINTIME
    error DepositForLockDurationTooShort();

    /// @notice Error thrown when trying to perform an operation on an expired lock
    error LockExpired();

    /// @notice Error thrown when trying to withdraw from a lock that hasn't expired yet
    error LockNotExpired();

    /// @notice Error thrown when no lock is found for the specified token ID
    error NoLockFound();

    /// @notice Error thrown when the caller is neither the owner nor approved for the token
    error NotApprovedOrOwner();

    /// @notice Error thrown when trying to unlock a non-permanent lock using unlockPermanent
    error NotPermanentLock();

    /// @notice Error thrown when the caller is not the owner of the token
    error NotOwner();

    /// @notice Error thrown when a team-only function is called by a non-team address
    error NotTeam();

    /// @notice Error thrown when a pending team function is called by a non-pending team address
    error NotPendingTeam();

    /// @notice Error thrown when trying to withdraw or modify a permanent lock
    error PermanentLock();

    /// @notice Error thrown when attempting to merge a veNFT with itself
    error SameNFT();

    /// @notice Error thrown when splitting is not allowed for the user
    error SplitNotAllowed();

    /// @notice Error thrown when trying to add a token that already has an owner
    error AlreadyOwned();

    /// @notice Error thrown when setting a revenue reward contract that is not a deployed contract
    error InvalidRevenueRewardContract();

    /**
     * @notice Emitted when tokens are deposited into the veNFT system
     * @param provider Address depositing the tokens
     * @param tokenId ID of the veNFT being created or modified
     * @param depositType Type of deposit operation (create, increase amount, etc.)
     * @param value Amount of tokens deposited
     * @param locktime Timestamp when the lock expires
     * @param ts Timestamp when the deposit occurred
     */
    event Deposit(
        address indexed provider,
        uint256 indexed tokenId,
        DepositType indexed depositType,
        uint256 value,
        uint256 locktime,
        uint256 ts
    );

    /**
     * @notice Emitted when tokens are withdrawn before the lock expiry with a penalty
     * @param provider Address receiving the withdrawn tokens
     * @param tokenId ID of the veNFT being withdrawn
     * @param value Original locked amount
     * @param amountReturned Amount returned to the user after penalty
     * @param ts Timestamp when the early withdrawal occurred
     */
    event EarlyWithdraw(
        address indexed provider, uint256 indexed tokenId, uint256 value, uint256 amountReturned, uint256 ts
    );

    /**
     * @notice Emitted when tokens are withdrawn after the lock expiry
     * @param provider Address receiving the withdrawn tokens
     * @param tokenId ID of the veNFT being withdrawn
     * @param value Amount of tokens withdrawn
     * @param ts Timestamp when the withdrawal occurred
     */
    event Withdraw(address indexed provider, uint256 indexed tokenId, uint256 value, uint256 ts);

    /**
     * @notice Emitted when a lock is converted to a permanent lock
     * @param _owner Address that owns the veNFT
     * @param _tokenId ID of the veNFT being locked permanently
     * @param amount Amount of tokens in the lock
     * @param _ts Timestamp when the permanent lock was created
     */
    event LockPermanent(address indexed _owner, uint256 indexed _tokenId, uint256 amount, uint256 _ts);

    /**
     * @notice Emitted when a permanent lock is unlocked by governance
     * @param _owner Address that owns the veNFT
     * @param _tokenId ID of the veNFT being unlocked
     * @param amount Amount of tokens in the lock
     * @param _ts Timestamp when the permanent lock was unlocked
     */
    event UnlockPermanent(address indexed _owner, uint256 indexed _tokenId, uint256 amount, uint256 _ts);

    /**
     * @notice Emitted when the total supply of locked tokens changes
     * @param prevSupply Previous total locked supply
     * @param supply New total locked supply
     */
    event Supply(uint256 prevSupply, uint256 supply);

    /**
     * @notice Emitted when two veNFTs are merged
     * @param _sender Address initiating the merge
     * @param _from Source veNFT ID (burned in the process)
     * @param _to Destination veNFT ID (receives combined balance)
     * @param _amountFrom Amount of tokens in the source veNFT
     * @param _amountTo Amount of tokens in the destination veNFT before merge
     * @param _amountFinal Final amount of tokens in the destination veNFT after merge
     * @param _locktime New lock expiry time for the merged veNFT
     * @param _ts Timestamp when the merge occurred
     */
    event Merge(
        address indexed _sender,
        uint256 indexed _from,
        uint256 indexed _to,
        uint256 _amountFrom,
        uint256 _amountTo,
        uint256 _amountFinal,
        uint256 _locktime,
        uint256 _ts
    );

    /**
     * @notice Emitted when a veNFT is split into two separate veNFTs
     * @param _from Original veNFT ID being split (burned in the process)
     * @param _tokenId1 First new veNFT ID created from the split
     * @param _tokenId2 Second new veNFT ID created from the split
     * @param _sender Address initiating the split
     * @param _splitAmount1 Amount of tokens allocated to the first veNFT
     * @param _splitAmount2 Amount of tokens allocated to the second veNFT
     * @param _locktime Lock expiry time for both new veNFTs
     * @param _ts Timestamp when the split occurred
     */
    event Split(
        uint256 indexed _from,
        uint256 indexed _tokenId1,
        uint256 indexed _tokenId2,
        address _sender,
        uint256 _splitAmount1,
        uint256 _splitAmount2,
        uint256 _locktime,
        uint256 _ts
    );

    /**
     * @notice Emitted when a new team address is proposed
     * @param currentTeam The current team address that proposed the change
     * @param proposedTeam The newly proposed team address
     */
    event TeamProposed(address indexed currentTeam, address indexed proposedTeam);

    /**
     * @notice Emitted when a proposed team address accepts ownership
     * @param oldTeam The previous team address
     * @param newTeam The new team address that accepted ownership
     */
    event TeamAccepted(address indexed oldTeam, address indexed newTeam);

    /**
     * @notice Emitted when a team proposal is cancelled
     * @param currentTeam The current team address that cancelled the proposal
     * @param cancelledTeam The proposed team address that was cancelled
     */
    event TeamProposalCancelled(address indexed currentTeam, address indexed cancelledTeam);

    /**
     * @notice Emitted when the early withdraw penalty is updated
     * @param oldPenalty Previous penalty in basis points
     * @param newPenalty New penalty in basis points
     */
    event EarlyWithdrawPenaltyUpdated(uint256 oldPenalty, uint256 newPenalty);

    /**
     * @notice Emitted when the early withdraw treasury address is updated
     * @param oldTreasury Previous treasury address
     * @param newTreasury New treasury address
     */
    event EarlyWithdrawTreasuryUpdated(address indexed oldTreasury, address indexed newTreasury);

    /**
     * @notice Emitted when the minimum lock amount is updated
     * @param oldAmount Previous minimum lock amount
     * @param newAmount New minimum lock amount
     */
    event MinLockAmountUpdated(uint256 oldAmount, uint256 newAmount);

    /**
     * @notice Emitted when the revenue reward contract is updated
     * @param oldReward Previous revenue reward contract address
     * @param newReward New revenue reward contract address
     */
    event RevenueRewardUpdated(address indexed oldReward, address indexed newReward);

    /**
     * @notice Emitted when the split permission is toggled for an account
     * @param account Address whose permission is updated
     * @param allowed Whether splitting is now allowed for the account
     */
    event SplitPermissionUpdated(address indexed account, bool allowed);

    /**
     * @notice Emitted when the base URI is updated
     * @param oldBaseURI Previous base URI
     * @param newBaseURI New base URI
     */
    event BaseURIUpdated(string oldBaseURI, string newBaseURI);

    /*//////////////////////////////////////////////////////////////
                                STATE VARIABLES
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Address of Meta-tx Forwarder
     * @return The trusted forwarder address used for meta-transactions
     */
    function forwarder() external view returns (address);

    /**
     * @notice Address of token (DUST) used to create a veNFT
     * @return The ERC20 token address used to lock and mint veNFTs
     */
    function token() external view returns (address);

    /**
     * @notice Address of Neverland Team multisig
     * @return The address of the current team multisig with administrative privileges
     */
    function team() external view returns (address);

    /**
     * @notice Address of pending team for two-step ownership transfer
     * @return The address of the pending team, or address(0) if no proposal exists
     */
    function pendingTeam() external view returns (address);

    /*//////////////////////////////////////////////////////////////
                                ADMIN
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Proposes a new team address for two-step ownership transfer
     * @dev This is the first step of a two-step ownership transfer process.
     *      Only the current team can propose a new team address.
     *      The proposed address must accept ownership to complete the transfer.
     *      This prevents accidental loss of admin control due to typos or wrong addresses.
     * @param _newTeam The address of the proposed new team multisig
     */
    function proposeTeam(address _newTeam) external;

    /**
     * @notice Accepts the proposed team address to complete the ownership transfer
     * @dev This is the second step of the two-step ownership transfer process.
     *      Only the pending team address can call this function.
     *      Once called, the caller becomes the new team and the pending team is cleared.
     *      This ensures that the new team controls the proposed address.
     */
    function acceptTeam() external;

    /**
     * @notice Cancels the pending team proposal
     * @dev Allows the current team to cancel a pending ownership transfer.
     *      Only the current team can call this function.
     *      This is useful if the team made an error in the proposed address.
     *      After cancellation, a new proposal can be made.
     */
    function cancelTeamProposal() external;

    /*///////////////////////////////////////////////////////////////
                             METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the name of the token
     * @return The name of the veNFT token
     */
    function name() external view returns (string memory);

    /**
     * @notice Returns the symbol of the token
     * @return The symbol of the veNFT token
     */
    function symbol() external view returns (string memory);

    /**
     * @notice Returns the version of the contract
     * @return The current version string of the contract
     */
    function version() external view returns (string memory);

    /**
     * @notice Updates the base URI for computing tokenURI
     * @dev Can only be called by the team address
     * @param newBaseURI The new base URI to set for all tokens
     */
    function setBaseURI(string memory newBaseURI) external;

    /**
     * @notice Current total count of veNFT tokens
     * @dev Used as a counter for minting new tokens and assigning IDs
     * @return The current highest token ID value
     */
    function tokenId() external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                      ERC721 BALANCE/OWNER STORAGE
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the tokenId owned by `_owner` at position `_index`
     * @param _owner Owner address to query
     * @param _index Index of the token within the owner's list
     * @return _tokenId The tokenId at the given index for the owner
     */
    function ownerToNFTokenIdList(address _owner, uint256 _index) external view returns (uint256 _tokenId);

    /// @inheritdoc IERC721
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /// @inheritdoc IERC721
    function balanceOf(address owner) external view returns (uint256 balance);

    /*//////////////////////////////////////////////////////////////
                         ERC721 APPROVAL STORAGE
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC721
    function getApproved(uint256 _tokenId) external view returns (address operator);

    /// @inheritdoc IERC721
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @notice Check whether spender is owner or an approved user for a given veNFT
     * @param _spender The address to approve for the tokenId
     * @param _tokenId The ID of the veNFT to be approved
     * @return True if `_spender` is owner or approved for `_tokenId`, false otherwise
     */
    function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool);

    /*//////////////////////////////////////////////////////////////
                              ERC721 LOGIC
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC721
    function approve(address to, uint256 tokenId) external;

    /// @inheritdoc IERC721
    function setApprovalForAll(address operator, bool approved) external;

    /// @inheritdoc IERC721
    function transferFrom(address from, address to, uint256 tokenId) external;

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /*//////////////////////////////////////////////////////////////
                              ERC165 LOGIC
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 _interfaceID) external view returns (bool);

    /*//////////////////////////////////////////////////////////////
                             ESCROW STORAGE
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Total count of epochs witnessed since contract creation
     * @return The current epoch number
     */
    function epoch() external view returns (uint256);

    /**
     * @notice Total amount of tokens currently locked in the contract
     * @return The total supply of locked tokens
     */
    function supply() external view returns (uint256);

    /**
     * @notice Aggregate balance of permanently locked tokens
     * @dev These tokens cannot be withdrawn through normal means
     * @return The total amount of permanently locked tokens
     */
    function permanentLockBalance() external view returns (uint256);

    /**
     * @notice Percentage of penalty applied to early withdrawals (in basis points)
     * @dev Value is between 0 and 10000 (0% to 100%)
     * @return The current penalty percentage in basis points
     */
    function earlyWithdrawPenalty() external view returns (uint256);

    /**
     * @notice Address that receives penalty fees from early withdrawals
     * @return The address of the treasury that collects early withdrawal penalties
     */
    function earlyWithdrawTreasury() external view returns (address);

    /**
     * @notice Get the current epoch number for a specific veNFT
     * @param _tokenId The ID of the veNFT to check
     * @return _epoch The current epoch number for the specified veNFT
     */
    function userPointEpoch(uint256 _tokenId) external view returns (uint256 _epoch);

    /**
     * @notice Retrieve the scheduled slope change at a given timestamp
     * @dev Used to calculate future voting power changes due to lock expirations
     * @param _timestamp The timestamp to check for slope changes
     * @return The net change in slope (negative value means decrease in voting power)
     */
    function slopeChanges(uint256 _timestamp) external view returns (int256);

    /**
     * @notice Check if an account has permission to split veNFTs
     * @dev Used to control which addresses can perform veNFT splitting operations
     * @param _account The address to check for split permission
     * @return True if the account can split veNFTs, false otherwise
     */
    function canSplit(address _account) external view returns (bool);

    /**
     * @notice Retrieve a global checkpoint at a specific index
     * @dev Used to track historical voting power across all tokens at different points in time
     * @param _loc The index of the checkpoint to retrieve
     * @return The GlobalPoint data at the specified index
     */
    function pointHistory(uint256 _loc) external view returns (GlobalPoint memory);

    /**
     * @notice Get the lock details for a specific veNFT
     * @dev Returns information about lock amount, end time, and permanent status
     * @param _tokenId The ID of the veNFT to query
     * @return The LockedBalance struct containing lock information
     */
    function locked(uint256 _tokenId) external view returns (LockedBalance memory);

    /**
     * @notice Retrieve a user checkpoint for a specific veNFT at a given index
     * @dev Used to track historical voting power for individual tokens
     * @param _tokenId The ID of the veNFT to query
     * @param _loc The index of the user checkpoint to retrieve
     * @return The UserPoint data at the specified index for the given token
     */
    function userPointHistory(uint256 _tokenId, uint256 _loc) external view returns (UserPoint memory);

    /*//////////////////////////////////////////////////////////////
                              ESCROW LOGIC
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Create a global checkpoint to record the current state of voting power
     * @dev Updates the global point history with current voting power data
     *      This is called automatically by most state-changing functions
     *      but can be called manually to ensure up-to-date on-chain data
     */
    function checkpoint() external;

    /**
     * @notice Deposit additional tokens for an existing veNFT lock
     * @dev Anyone (even a smart contract) can deposit tokens for someone else's lock
     *      The deposit increases the lock amount but does not extend the lock time
     *      Cannot be used for locks that have already expired
     * @param _tokenId The ID of the veNFT to deposit for
     * @param _value Amount of tokens to add to the existing lock
     */
    function depositFor(uint256 _tokenId, uint256 _value) external;

    /**
     * @notice Create a new lock by depositing tokens for the caller
     * @dev Creates a new veNFT representing the locked tokens
     *      Lock duration is rounded down to the nearest week
     * @param _value Amount of tokens to deposit and lock
     * @param _lockDuration Number of seconds to lock tokens for (rounded down to nearest week)
     * @return The ID of the newly created veNFT
     */
    function createLock(uint256 _value, uint256 _lockDuration) external returns (uint256);

    /**
     * @notice Create a new lock by depositing tokens for another address
     * @dev Creates a new veNFT representing the locked tokens and assigns it to the specified recipient
     *      This is useful for protocols that want to create locks on behalf of their users
     *      Lock duration is rounded down to the nearest week
     * @param _value Amount of tokens to deposit and lock
     * @param _lockDuration Number of seconds to lock tokens for (rounded down to nearest week)
     * @param _to The address that will own the newly created veNFT
     * @return The ID of the newly created veNFT
     */
    function createLockFor(uint256 _value, uint256 _lockDuration, address _to) external returns (uint256);

    /**
     * @notice Create a new lock for the caller and immediately make it permanent
     * @dev UX convenience to perform "create lock" and "make permanent" in a single transaction
     *      Follows the same validation as `createLock` (min amount, duration bounds, week rounding)
     * @param _value Amount of tokens to deposit and lock
     * @param _lockDuration Number of seconds to lock tokens for (rounded down to nearest week)
     * @return tokenId The ID of the newly created veNFT
     */
    function createLockPermanent(uint256 _value, uint256 _lockDuration) external returns (uint256);

    /**
     * @notice Create a new lock for `to` and immediately make it permanent
     * @dev UX convenience to mint the veNFT to `to` and set permanence in one transaction
     *      Uses `to` as the owner for auth semantics; validation mirrors `createLock`
     * @param _value Amount of tokens to deposit and lock
     * @param _lockDuration Number of seconds to lock tokens for (rounded down to nearest week)
     * @param _to The address that will own the newly created veNFT
     * @return tokenId The ID of the newly created veNFT
     */
    function createLockPermanentFor(uint256 _value, uint256 _lockDuration, address _to) external returns (uint256);

    /**
     * @notice Deposit additional tokens for an existing veNFT without modifying the unlock time
     * @dev Increases the amount of tokens in a lock while keeping the same unlock date
     *      Can only be called by the owner of the veNFT or an approved address
     * @param _tokenId The ID of the veNFT to increase the amount for
     * @param _value Additional amount of tokens to add to the lock
     */
    function increaseAmount(uint256 _tokenId, uint256 _value) external;

    /**
     * @notice Extend the unlock time for an existing veNFT lock
     * @dev Increases the lock duration without changing the token amount
     *      Cannot extend lock time of permanent locks
     *      New lock time is rounded down to the nearest week
     *      Can only be called by the owner of the veNFT or an approved address
     * @param _tokenId The ID of the veNFT to extend the lock duration for
     * @param _lockDuration New number of seconds until tokens unlock (from current time)
     */
    function increaseUnlockTime(uint256 _tokenId, uint256 _lockDuration) external;

    /**
     * @notice Withdraw all tokens from an expired lock for `_tokenId`
     * @dev Only possible if the lock has expired and is not a permanent lock
     *      This function burns the veNFT and returns the locked tokens to the owner
     *      IMPORTANT: Any unclaimed rebases or rewards will no longer be claimable after calling this
     *      Users should claim all rebases and rewards prior to withdrawing
     *      Can only be called by the owner of the veNFT or an approved address
     * @param _tokenId The ID of the veNFT to withdraw tokens from
     */
    function withdraw(uint256 _tokenId) external;

    /**
     * @notice Withdraw tokens from a lock before it expires, with a time-proportional penalty
     * @dev Allows users to exit a lock early but with a penalty fee applied
     *      The penalty is proportional to both `earlyWithdrawPenalty` and remaining time until unlock
     *      If the lock is permanent, it is internally converted back to a standard time-lock first and
     *      the early withdraw penalty is computed using the restored lock window. Penalty fees are sent
     *      to the `earlyWithdrawTreasury` address. Burns the veNFT and returns the non‑penalized portion
     *      of tokens to the owner. Can only be called by the owner of the veNFT or an approved address
     * @param _tokenId The ID of the veNFT to withdraw early from
     */
    function earlyWithdraw(uint256 _tokenId) external;

    /**
     * @notice Sets the early withdrawal penalty percentage
     * @dev Can only be called by the team address
     *      Value is in basis points (0-10000), where 10000 = 100%
     * @param _earlyWithdrawPenalty The new penalty percentage in basis points
     */
    function setEarlyWithdrawPenalty(uint256 _earlyWithdrawPenalty) external;

    /**
     * @notice Sets the treasury address that will receive penalty fees from early withdrawals
     * @dev Can only be called by the team address
     *      The treasury address receives the penalty portion of tokens from early withdrawals
     * @param _account The address of the new treasury that will receive penalty fees
     */
    function setEarlyWithdrawTreasury(address _account) external;

    /**
     * @notice Merges two veNFTs by combining their locked tokens into a single veNFT
     * @dev The source veNFT is burned and its tokens are added to the destination veNFT
     *      The lock duration/semantics of the destination veNFT are preserved
     *      Rules:
     *      - permanent + permanent: allowed (destination stays permanent)
     *      - non‑permanent + permanent: allowed (permanent principal increases)
     *      - permanent + non‑permanent: reverts
     *      - expired source or destination: reverts
     *      Can only be called by an address that owns or is approved for both veNFTs
     * @param _from The ID of the source veNFT to merge from (will be burned)
     * @param _to The ID of the destination veNFT to merge into (will receive the combined tokens)
     */
    function merge(uint256 _from, uint256 _to) external;

    /**
     * @notice Splits a veNFT into two new veNFTs with divided token balances
     * @dev This operation burns the original veNFT and creates two new ones
     *      Both new veNFTs maintain the same lock end time as the original
     *      Can only be called by an address that has split permission, and owns or is approved for the veNFT
     *      If called by an approved address, that address will NOT have approval on the new veNFTs
     *      (approvals on the parent do not carry over to children)
     *      Requires that the caller is either the owner or specifically has been granted split permission
     *      Cannot split permanent locks
     * @param _from The ID of the veNFT to split (will be burned)
     * @param _amount The precise token amount to allocate to the second new veNFT
     * @return _tokenId1 ID of the first new veNFT with (original amount - _amount) tokens
     * @return _tokenId2 ID of the second new veNFT with exactly _amount tokens
     */
    function split(uint256 _from, uint256 _amount) external returns (uint256 _tokenId1, uint256 _tokenId2);

    /**
     * @notice Grant or revoke permission for an address to split veNFTs
     * @dev Can only be called by the team address
     *      Setting permissions for address(0) acts as a global switch for all addresses
     *      If address(0) is set to false, no address can split regardless of individual permissions
     *      If address(0) is set to true, individual permissions apply normally
     * @param _account The address to modify split permissions for, or address(0) for global setting
     * @param _bool True to grant permission, false to revoke permission
     */
    function toggleSplit(address _account, bool _bool) external;

    /**
     * @notice Permanently lock a veNFT to give it non-decaying voting power
     * @dev Converts a standard time-locked veNFT to a permanent lock
     *      Once permanent, the veNFT cannot be withdrawn normally (even after the original lock time)
     *      Permanent locks have constant voting power equal to the locked token amount with no time decay
     *      Note: time served prior to permanence is not preserved for penalty calculations — if the owner
     *      later calls `earlyWithdraw`, the position is first unlocked and the penalty window resets to a
     *      full MAXTIME from the current timestamp
     *      Can only be called by the owner of the veNFT or an approved address
     *      Cannot be called on a lock that is already permanent
     * @param _tokenId The ID of the veNFT to permanently lock
     */
    function lockPermanent(uint256 _tokenId) external;

    /**
     * @notice Revert a veNFT from permanent lock status back to a standard time-lock
     * @dev Converts a permanent lock back to a standard time-based lock
     *      After unlocking, the veNFT's voting power will decay based on the remaining lock time
     *      The lock time will be the original lock end time from before it was made permanent
     *      If the original lock time has already passed, the lock will be immediately withdrawable
     *      Can only be called by the owner or an approved operator
     *      Only callable on veNFTs that are currently permanently locked
     * @param _tokenId The ID of the veNFT to revert from permanent to standard lock
     */
    function unlockPermanent(uint256 _tokenId) external;

    /*///////////////////////////////////////////////////////////////
                           VOTING POWER STORAGE
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Get the current voting power for a specific veNFT
     * @dev Calculates voting power based on lock amount, remaining time, and permanent status
     *      For standard locks: voting power = amount * (time_left / MAXTIME)
     *      For permanent locks: voting power = amount (no time decay)
     *      Returns 0 if called in the same block as a transfer due to checkpoint timing
     *      This is the core function used for governance voting power determination
     * @param _tokenId The ID of the veNFT to query voting power for
     * @return The current voting power of the specified veNFT
     */
    function balanceOfNFT(uint256 _tokenId) external view returns (uint256);

    /**
     * @notice Get the historical voting power for a veNFT at a specific timestamp
     * @dev Uses checkpoints to determine voting power at any point in the past
     *      Crucial for governance systems that need to determine past voting power
     *      For timestamps between checkpoints, calculates the interpolated value
     *      Returns 0 for timestamps before the veNFT was created
     * @param _tokenId The ID of the veNFT to query historical voting power for
     * @param _t The timestamp at which to query the voting power
     * @return The voting power of the specified veNFT at the requested timestamp
     */
    function balanceOfNFTAt(uint256 _tokenId, uint256 _t) external view returns (uint256);

    /**
     * @notice Calculate the total voting power across all veNFTs at the current timestamp
     * @dev Sums up all individual veNFT voting powers including both time-based and permanent locks
     *      This represents the total governance voting power in the system right now
     * @return The aggregate voting power of all veNFTs at the current timestamp
     */
    function totalSupply() external view returns (uint256);

    /**
     * @notice Calculate the total historical voting power across all veNFTs at a specific timestamp
     * @dev Uses global checkpoints to determine total voting power at any point in the past
     *      Critical for governance votes that need to determine the total voting power at a past block
     *      For timestamps between checkpoints, calculates the interpolated value
     * @param _t The timestamp at which to query the total voting power
     * @return The aggregate voting power of all veNFTs at the requested timestamp
     */
    function totalSupplyAt(uint256 _t) external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                              ERC6372 LOGIC
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC6372
    function clock() external view returns (uint48);

    /// @inheritdoc IERC6372
    function CLOCK_MODE() external view returns (string memory);

    /*//////////////////////////////////////////////////////////////
                          MIN LOCK AMOUNT
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the minimum amount of tokens required to create a veNFT lock
     * @dev This value is used to validate lock creation and prevent spam attacks
     * @return The minimum lock amount in token units (with 18 decimals)
     */
    function minLockAmount() external view returns (uint256);

    /**
     * @notice Sets the minimum amount of tokens required to create a veNFT lock
     * @dev Can only be called by the team address. This helps prevent spam and ensures meaningful lock amounts
     * @param newMinLockAmount The new minimum lock amount in token units (with 18 decimals)
     */
    function setMinLockAmount(uint256 newMinLockAmount) external;

    /*//////////////////////////////////////////////////////////////
                      NOTIFY CONTRACTS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the revenue reward contract
     * @dev Returns address(0) if no revenue reward contract is set
     * @return The revenue reward contract
     */
    function revenueReward() external view returns (IRevenueReward);

    /**
     * @notice Sets the revenue reward contract
     * @dev Can only be called by the team address
     * @param _revenueReward The new revenue reward contract
     */
    function setRevenueReward(IRevenueReward _revenueReward) external;
}

File 22 of 26 : IRevenueReward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

import {IDustLock} from "../interfaces/IDustLock.sol";

import {IUserVaultFactory} from "./IUserVaultFactory.sol";

/**
 * @title IRevenueReward Interface
 * @author Neverland
 * @notice Interface for the RevenueReward contract that manages token rewards distribution
 * @dev Handles reward epochs, claiming rewards, and self-repaying loan functionality
 */
interface IRevenueReward {
    /// @notice Error thrown when a non-distributor address attempts to notify rewards
    error NotRewardDistributor();

    /// @notice Error thrown when a non-owner address attempts a restricted operation
    error NotOwner();

    /// @notice Error thrown when a non-DustLock address attempts a restricted operation
    error NotDustLock();

    /// @notice Error thrown when end timestamp used for calculating rewards is greater than the current time
    error EndTimestampMoreThanCurrent();

    /// @notice Error thrown when provided arrays are empty or exceed soft size limits
    error InvalidArrayLengths();

    /// @notice Error thrown when a provided reward token is not registered
    error UnknownRewardToken();

    /// @notice Error thrown when an array contains duplicate values or is not sorted in ascending order
    error ArrayNotSortedOrContainsDuplicates();

    /**
     * @notice Emitted when rewards are claimed
     * @param tokenId The veNFT id that produced the rewards
     * @param user The address that received the rewards (owner or configured receiver)
     * @param token Address of the reward token being claimed
     * @param amount Amount of rewards claimed
     */
    event ClaimRewards(uint256 indexed tokenId, address indexed user, address indexed token, uint256 amount);

    /**
     * @notice Emitted when new rewards are notified to the contract
     * @param from Address that notified the rewards (typically the reward distributor)
     * @param token Address of the reward token being added
     * @param epoch Reward epoch start timestamp (i.e., start of the week) the amount is credited to
     * @param amount Amount of rewards added
     */
    event NotifyReward(address indexed from, address indexed token, uint256 epoch, uint256 amount);

    /**
     * @notice Emitted when tokens are recovered from the contract
     * @param token Address of the token being recovered
     * @param amount Amount of tokens recovered
     */
    event RecoverTokens(address indexed token, uint256 amount);

    /**
     * @notice Emitted when self-repaying loan status is updated for a token
     * @param token ID of the veNFT whose reward redirection is being configured
     * @param rewardReceiver Address that will receive the rewards (or zero address if disabled)
     * @param isEnabled Whether self-repaying loan is being enabled (true) or disabled (false)
     */
    event SelfRepayingLoanUpdate(uint256 indexed token, address rewardReceiver, bool isEnabled);

    /**
     * @notice Emitted when the reward distributor address is updated
     * @param oldDistributor The previous reward distributor
     * @param newDistributor The new reward distributor
     */
    event RewardDistributorUpdated(address indexed oldDistributor, address indexed newDistributor);

    /*//////////////////////////////////////////////////////////////
                                CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice The address of the DustLock contract that manages veNFTs
     * @return The IDustLock interface of the connected DustLock contract
     */
    function dustLock() external view returns (IDustLock);

    /**
     * @notice The address of the UserVaultFactory contract that manages user vaults
     * @return The IUserVaultFactory interface of the connected UserVaultFactory contract
     */
    function userVaultFactory() external view returns (IUserVaultFactory);

    /**
     * @notice The duration of a reward epoch in seconds
     * @dev This defines the time window for each reward distribution cycle
     * @return Duration in seconds for each reward epoch
     */
    function DURATION() external view returns (uint256);

    /**
     * @notice Maximum number of tokenIds allowed in a single batch claim.
     * @return The maximum number of tokenIds accepted in batch calls
     */
    function MAX_TOKENIDS() external view returns (uint256);

    /**
     * @notice Maximum number of reward tokens allowed in a single batch claim.
     * @return The maximum number of reward tokens accepted in batch calls
     */
    function MAX_TOKENS() external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                            STORAGE GETTERS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the timestamp of the last successfully processed reward claim for a token and veNFT
     * @dev Used to calculate the amount of rewards earned since the last claim. Value is advanced to the
     *      claim period end only when there were epochs to process; otherwise it remains unchanged.
     * @param token The address of the reward token
     * @param tokenId The ID of the veNFT
     * @return The timestamp (seconds) when rewards were last processed up to
     */
    function lastEarnTime(address token, uint256 tokenId) external view returns (uint256);

    /**
     * @notice Returns the address authorized to add rewards to the contract
     * @dev This address is the only one that can call notifyRewardAmount
     *      Typically set to a protocol treasury or governance-controlled address
     * @return The current reward distributor address
     */
    function rewardDistributor() external view returns (address);

    /**
     * @notice Checks if a token is registered as a valid reward token
     * @dev Only registered reward tokens can be distributed through the contract
     *      Tokens are registered automatically the first time they're used in notifyRewardAmount
     * @param token The address of the token to check
     * @return True if the token is registered as a reward token, false otherwise
     */
    function isRewardToken(address token) external view returns (bool);

    /**
     * @notice Returns the reward token at a specific index in the list of registered reward tokens
     * @dev Used to enumerate all reward tokens available in the contract
     *      Valid indices range from 0 to the number of registered reward tokens minus 1
     * @param index The index in the reward tokens array
     * @return The address of the reward token at the specified index
     */
    function rewardTokens(uint256 index) external view returns (address);

    /**
     * @notice Returns the accumulated sum of all reward distributions for a specific token
     * @dev Used for internal reward accounting and distribution calculations
     *      This value increases each time new rewards are notified
     * @param token The address of the reward token
     * @return The total amount of rewards ever distributed for this token
     */
    function totalRewardsPerToken(address token) external view returns (uint256);

    /**
     * @notice Returns the amount of rewards allocated for a specific token at a given epoch start
     * @dev Rewards are tracked by epoch start timestamp (seconds), with each epoch lasting DURATION seconds.
     * @param token The address of the reward token
     * @param epoch The epoch start timestamp (i.e., start of the week)
     * @return The amount of rewards allocated for the token at that epoch start
     */
    function tokenRewardsPerEpoch(address token, uint256 epoch) external view returns (uint256);

    /**
     * @notice Returns the timestamp when a veNFT was minted
     * @param tokenId The ID of the veNFT
     * @return The timestamp when the veNFT was minted
     */
    function tokenMintTime(uint256 tokenId) external view returns (uint256);

    /**
     * @notice Returns the accumulated fractional remainder of rewards for a veNFT and token, scaled by 1e18.
     * @dev During per-epoch reward calculations, integer division can leave a remainder that cannot be paid out.
     *      This function exposes the running sum of those remainders for the given (token, tokenId) pair,
     *      scaled by a factor of 1e18 to preserve precision (i.e., value is remainder * 1e18 / totalSupplyAt(epoch)).
     *      This value is informational and not directly claimable; it helps off-chain analytics understand
     *      the uncredited fractional rewards that have accumulated over time due to rounding.
     * @param token The address of the reward token being tracked.
     * @param tokenId The ID of the veNFT whose fractional remainder is queried.
     * @return scaledRemainder The accumulated fractional rewards remainder, scaled by 1e18.
     */
    function tokenRewardsRemainingAccScaled(address token, uint256 tokenId) external view returns (uint256);

    /**
     * @notice Returns the configured reward recipient address for a specific veNFT
     * @dev When self-repaying loan functionality is enabled, rewards are sent to this address
     *      Returns address(0) if no special recipient is configured (rewards go to veNFT owner)
     * @param tokenId The ID of the veNFT to query
     * @return The address that receives rewards for this veNFT, or address(0) if it's the owner
     */
    function tokenRewardReceiver(uint256 tokenId) external view returns (address);

    /*//////////////////////////////////////////////////////////////
                                ADMIN
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Updates the address authorized to add rewards to the contract
     * @dev Can only be called by the current reward distributor
     *      This is a critical permission that controls who can distribute rewards
     * @param newRewardDistributor The address of the new reward distributor
     */
    function setRewardDistributor(address newRewardDistributor) external;

    /**
     * @notice Adds new rewards to the distribution pool for the next epoch
     * @dev Can only be called by the authorized reward distributor address.
     *      Automatically registers new tokens the first time they're used.
     *      Rewards added during the current epoch become claimable starting the next epoch.
     *      Emits a NotifyReward event with details about the distribution.
     *      Reverts: NotRewardDistributor, zero address/amount checks enforced by implementation.
     * @param token The address of the reward token to distribute
     * @param amount The amount of rewards to add to the distribution pool
     */
    function notifyRewardAmount(address token, uint256 amount) external;

    /**
     * @notice Recovers unnotified balances of registered reward tokens
     * @dev Can only be called by the reward distributor
     *      For each registered reward token, if the contract's token balance exceeds the credited amount
     *      tracked by totalRewardsPerToken[token], transfers the excess to the reward distributor and emits
     *      a RecoverTokens event.
     */
    function recoverTokens() external;

    /*//////////////////////////////////////////////////////////////
                            NOTIFICATIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Notifies the contract that a new token has been created
     * @dev Intended to update internal state or trigger logic after a veNFT creation event
     *      Can only be called by the DustLock contract.
     * @param tokenId The ID of the token (veNFT) that has been created
     */
    function notifyTokenMinted(uint256 tokenId) external;

    /**
     * @notice Handles necessary operations after a veNFT token is transferred
     * @dev This function is called by the DustLock contract just after transferring a token
     *      It performs two main actions:
     *      1. Claims all pending rewards for the token being transferred
     *      2. Removes the token from the self-repaying loan tracking if enabled
     *      Can only be called by the DustLock contract.
     * @param tokenId The ID of the veNFT token that was transferred
     * @param from The address of the previous token owner (sender of the transfer)
     */
    function notifyAfterTokenTransferred(uint256 tokenId, address from) external;

    /**
     * @notice Handles necessary operations after a veNFT token is burned
     * @dev This function is called by the DustLock contract just after burning a token
     *      It performs two main actions:
     *      1. Claims all pending rewards for the token being burned
     *      2. Removes the token from the self-repaying loan tracking if enabled
     *      Can only be called by the DustLock contract.
     * @param tokenId The ID of the veNFT token that was burned
     * @param from The address of the previous token owner
     */
    function notifyAfterTokenBurned(uint256 tokenId, address from) external;

    /**
     * @notice Handles bookkeeping after two veNFTs are merged.
     * @dev Callable only by the DustLock contract.
     * @param fromToken The tokenId that was merged and is no longer active (source).
     * @param toToken The tokenId that survives the merge and should receive consolidated accounting (destination).
     * @param owner The tokens' owner.
     */
    function notifyAfterTokenMerged(uint256 fromToken, uint256 toToken, address owner) external;

    /**
     * @notice Handles bookkeeping after a veNFT is split into two new veNFTs.
     * @dev Callable only by the DustLock contract.
     *      - Initializes mint timestamps for the two new tokenIds.
     *      - Proportionally splits the accumulated fractional rewards remainder (scaled by 1e18)
     *        from `fromToken` between `tokenId1` and `tokenId2` using their provided amounts.
     *      - Clears the remainder accumulator for `fromToken` and removes it from any self-repaying
     *        loan tracking if applicable.
     * @param fromToken The original tokenId that was split (source).
     * @param tokenId1 The first resulting tokenId after the split.
     * @param token1Amount The amount (voting power/shares) assigned to `tokenId1` in the split.
     * @param tokenId2 The second resulting tokenId after the split.
     * @param token2Amount The amount (voting power/shares) assigned to `tokenId2` in the split.
     * @param owner The owner of the tokens involved in the split.
     */
    function notifyAfterTokenSplit(
        uint256 fromToken,
        uint256 tokenId1,
        uint256 token1Amount,
        uint256 tokenId2,
        uint256 token2Amount,
        address owner
    ) external;

    /*//////////////////////////////////////////////////////////////
                               CLAIMING
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Claims accumulated rewards for a specific veNFT across multiple reward tokens
     * @dev Calculates earned rewards for each specified token using epoch-based accounting and transfers them
     *      to the appropriate recipient. Emits a ClaimRewards event per token. If a reward receiver is configured
     *      via enableSelfRepayLoan, rewards go to that address; otherwise, rewards are sent to the veNFT owner.
     *      Updates lastEarnTime to track future accruals (only if there were epochs to process).
     *      Access: callable by the veNFT owner or an approved operator. The DustLock contract may also call.
     *      Reverts: NotOwner, UnknownRewardToken, InvalidArrayLengths.
     * @param tokenId The ID of the veNFT to claim rewards for
     * @param tokens Array of reward token addresses to claim (must be registered reward tokens)
     */
    function getReward(uint256 tokenId, address[] calldata tokens) external;

    /**
     * @notice Claims accumulated rewards for a specific veNFT across multiple reward tokens up to a specified timestamp
     * @dev Similar to getReward, but allows specifying a custom end timestamp for the reward calculation period.
     *      Calculates earned rewards for each specified token using epoch-based accounting and transfers them to the
     *      appropriate recipient. Emits a ClaimRewards event per token. If a reward receiver is configured via
     *      enableSelfRepayLoan, rewards go to that address; otherwise, rewards are sent to the veNFT owner.
     *      Updates lastEarnTime to rewardPeriodEndTs to track future accruals (only if there were epochs to process).
     *      Access: callable by the veNFT owner or an approved operator. The DustLock contract may also call.
     *      Reverts: NotOwner, EndTimestampMoreThanCurrent, UnknownRewardToken, InvalidArrayLengths.
     * @param tokenId The ID of the veNFT to claim rewards for
     * @param tokens Array of reward token addresses to claim (must be registered reward tokens)
     * @param rewardPeriodEndTs The end timestamp to calculate rewards up to (must not be in the future)
     */
    function getRewardUntilTs(uint256 tokenId, address[] calldata tokens, uint256 rewardPeriodEndTs) external;

    /**
     * @notice Batch claim rewards for many tokenIds across a set of tokens.
     * @dev Access: callable by the veNFT owner or an approved operator. Reverts on invalid arrays or unknown tokens.
     * @param tokenIds Array of veNFT ids to claim for.
     * @param tokens Array of reward token addresses to claim.
     */
    function getRewardBatch(uint256[] calldata tokenIds, address[] calldata tokens) external;

    /**
     * @notice Batch claim rewards for many tokenIds across a set of tokens up to a specific timestamp.
     * @dev Access: callable by the veNFT owner or an approved operator. Reverts on invalid arrays, unknown tokens,
     *      or if `rewardPeriodEndTs` is in the future.
     * @param tokenIds Array of veNFT ids to claim for.
     * @param tokens Array of reward token addresses to claim.
     * @param rewardPeriodEndTs End timestamp for calculation (<= now).
     */
    function getRewardUntilTsBatch(uint256[] calldata tokenIds, address[] calldata tokens, uint256 rewardPeriodEndTs)
        external;

    /*//////////////////////////////////////////////////////////////
                         SELF-REPAYING LOANS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Enables the self-repaying loan feature for a specific veNFT
     * @dev Configures a custom reward receiver address (typically a loan contract).
     *      This allows veNFT owners to use their rewards to automatically repay loans.
     *      The getReward function must still be called to trigger the reward claim.
     *      Access: callable only by the veNFT owner.
     *      Reverts: NotOwner, zero rewardReceiver.
     * @param tokenId The ID of the veNFT to configure self-repaying loan for
     */
    function enableSelfRepayLoan(uint256 tokenId) external;

    /**
     * @notice Disables the self-repaying loan feature for a specific veNFT
     * @dev Removes the custom reward receiver configuration, returning to default behavior.
     *      After disabling, all future rewards will go directly to the veNFT owner.
     *      Access: callable only by the veNFT owner.
     *      Reverts: NotOwner.
     * @param tokenId The ID of the veNFT to restore default reward routing for
     */
    function disableSelfRepayLoan(uint256 tokenId) external;

    /**
     * @notice Batch enable self-repaying loan with a single receiver for many tokenIds.
     * @dev Each tokenId must be owned by the caller. Reverts on zero rewardReceiver.
     * @param tokenIds Array of veNFT ids to configure.
     */
    function enableSelfRepayLoanBatch(uint256[] calldata tokenIds) external;

    /**
     * @notice Batch disable self-repaying loan for many tokenIds.
     * @dev Each tokenId must be owned by the caller.
     * @param tokenIds Array of veNFT ids to restore default reward routing.
     */
    function disableSelfRepayLoanBatch(uint256[] calldata tokenIds) external;

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Preview unclaimed rewards for a single reward token up to a specific timestamp.
     * @dev Read-only mirror of claim math; does not mutate state, does not advance checkpoints.
     *      Reverts: EndTimestampMoreThanCurrent if `endTs` is in the future, UnknownRewardToken if not registered.
     * @param token Reward token address to preview.
     * @param tokenId veNFT id to preview for.
     * @param endTs Timestamp (<= now) up to which to compute rewards.
     * @return amount Total rewards that would be claimable if claimed up to `endTs`.
     */
    function earnedRewards(address token, uint256 tokenId, uint256 endTs) external view returns (uint256 amount);

    /**
     * @notice Preview unclaimed rewards for multiple tokenIds and multiple tokens at the current timestamp.
     * @dev Convenience wrapper that uses block.timestamp internally. Returns a matrix of rewards per
     *      tokenId (outer) per token (inner), and totals per token.
     *      Reverts: InvalidArrayLengths on bad inputs, UnknownRewardToken if a token is not registered.
     * @param tokens Array of reward token addresses.
     * @param tokenIds Array of veNFT ids.
     * @return matrix Rewards matrix with shape [tokenIds.length][tokens.length].
     * @return totals Totals per token across all tokenIds with shape [tokens.length].
     */
    function earnedRewardsAll(address[] calldata tokens, uint256[] calldata tokenIds)
        external
        view
        returns (uint256[][] memory matrix, uint256[] memory totals);

    /**
     * @notice Preview unclaimed rewards for multiple tokenIds and multiple tokens up to a specific timestamp.
     * @dev Read-only; does not mutate state, does not advance checkpoints.
     *      Reverts: EndTimestampMoreThanCurrent if `endTs` is in the future, InvalidArrayLengths on bad inputs,
     *      UnknownRewardToken if a token is not registered.
     * @param tokens Array of reward token addresses.
     * @param tokenIds Array of veNFT ids.
     * @param endTs Timestamp (<= now) up to which to compute rewards.
     * @return matrix Rewards matrix with shape [tokenIds.length][tokens.length].
     * @return totals Totals per token across all tokenIds with shape [tokens.length].
     */
    function earnedRewardsAllUntilTs(address[] calldata tokens, uint256[] calldata tokenIds, uint256 endTs)
        external
        view
        returns (uint256[][] memory matrix, uint256[] memory totals);

    /**
     * @notice Returns the number of registered reward tokens
     * @return The count of reward tokens
     */
    function rewardTokensLength() external view returns (uint256);

    /**
     * @notice Returns the full list of registered reward tokens
     * @return tokens An array containing all reward token addresses
     */
    function getRewardTokens() external view returns (address[] memory tokens);

    /**
     * @notice Returns a list of user addresses with at least one active self-repaying loan within a given range.
     * @dev Iterates over the internal set of users who have enabled self-repaying loans,
     *      returning addresses from index `from` up to, but not including, index `to`.
     *      If the specified range exceeds the number of users, the function adjusts accordingly.
     * @param from The starting index (inclusive) in the user set.
     * @param to The ending index (exclusive) in the user set.
     * @return users An array of user addresses in the specified range who have self-repaying loans enabled.
     */
    function getUsersWithSelfRepayingLoan(uint256 from, uint256 to) external view returns (address[] memory);

    /**
     * @notice Returns the list of token IDs for which the given user has enabled a self-repaying loan.
     * @dev Checks the user's internal set of token IDs with self-repaying loans and returns them as an array.
     * @param user The address of the user to query.
     * @return tokenIds An array of token IDs currently associated with self-repaying loans for the user.
     */
    function getUserTokensWithSelfRepayingLoan(address user) external view returns (uint256[] memory tokenIds);
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/**
 * @title IUserVault
 * @author Neverland
 * @notice Interface for UserVault: manage repayments, swaps, and recoveries
 */
interface IUserVault {
    /// @notice Emitted when an aggregator is not supported.
    error AggregatorNotSupported();
    ///  @notice Emitted when the caller is not the executor
    error NotExecutor();
    /// @notice Emitted when swap is failed
    error SwapFailed();
    /// @notice Emitted the asset prices failed to be retrieved from oracle
    error GettingAssetPriceFailed();
    /// @notice Emitted when swapping slippage exceeded the max allowed
    error SlippageExceeded();
    /// @notice Emitted when tokenId belongs to a different user vault
    error InvalidUserVaultForToken();
    /// @notice Emitted max slippage set by execute is more than max allowed
    error MaxSlippageTooHigh();
    /// @notice Emitted user poolAddressesProvider is not registered in poolAddressesProviderRegistry
    error InvalidPoolAddressesProvider();
    /// @notice Emitted when native ETH send fails during recovery
    error ETHSendFailed();

    /**
     * @notice Emitted when a user's loan is repaid through the vault
     * @param user The loan owner's address
     * @param userVault The UserVault that executed the repayment
     * @param poolAddressesProvider The Aave pool addresses provider used
     * @param debtToken The repaid debt token address
     * @param amount The repaid amount
     */
    event LoanSelfRepaid(
        address indexed user,
        address indexed userVault,
        address poolAddressesProvider,
        address debtToken,
        uint256 amount
    );

    /*//////////////////////////////////////////////////////////////
                                STRUCTS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Parameters for repaying a user's debt on a lending pool.
     * @dev
     * - tokenIds must belong to this user vault, otherwise the call reverts.
     * - Set aggregatorAddress and aggregatorData only if a swap is required (e.g., swapping rewards to the debt token).
     * - maxSlippageBps is expressed in basis points (1 bps = 0.01%).
     * @param debtToken The address of the debt token to be repaid.
     * @param poolAddressesProvider The pool address provider of the pool, where the debt exists.
     * @param tokenIds List of token IDs involved in the operation.
     * @param rewardToken The reward token to claim and optionally swap before repayment.
     * @param rewardTokenAmountToSwap Amount of rewardToken to swap into the debt token.
     * @param aggregatorAddress Swap aggregator address to use for asset conversion, if needed.
     * @param aggregatorData Calldata for the aggregator to perform the swap.
     * @param maxSlippageBps Maximum acceptable swap slippage in basis points.
     */
    struct RepayUserDebtParams {
        address debtToken;
        address poolAddressesProvider;
        uint256[] tokenIds;
        address rewardToken;
        uint256 rewardTokenAmountToSwap;
        address aggregatorAddress;
        bytes aggregatorData;
        uint256 maxSlippageBps;
    }

    /*//////////////////////////////////////////////////////////////
                                ACTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Repays a user's debt for a specified token on a lending pool
     * @dev Optionally claims rewardToken and swaps it via the provided aggregator before repayment,
     *      enforcing the specified maxSlippageBps. Reverts if tokenIds are not associated with this vault
     * @param params Structured parameters. See RepayUserDebtParams for details
     */
    function repayUserDebt(RepayUserDebtParams calldata params) external;

    /**
     * @notice Claims rewards for the provided tokenIds and returns the total amount of rewardToken received.
     * @dev
     * - Reverts with InvalidUserVaultForToken if any tokenId’s reward receiver is not this vault
     * - Calls the external rewards distributor for each tokenId to pull rewards into this contract
     * - Computes the claimed amount by measuring this contract’s rewardToken balance delta
     * - Callable only by the executor; otherwise reverts with NotExecutor
     * @param tokenIds Array of token IDs whose rewards should be claimed
     * @param rewardToken The ERC20 reward token to claim
     * @return rewardTokenAmount The total amount of rewardToken claimed into this vault
     */
    function getTokenIdsReward(uint256[] memory tokenIds, address rewardToken) external returns (uint256);

    /**
     * @notice Swaps tokenIn for tokenOut via a supported aggregator and verifies slippage against oracle prices.
     * @dev
     * - Reverts with AggregatorNotSupported if the aggregator is not approved
     * - Forwards aggregatorData to the aggregator using a low-level call; reverts with SwapFailed on failure
     * - Computes USD-denominated slippage using oracle prices and reverts with SlippageExceeded
     *   if it exceeds maxAllowedSlippageBps
     * - Callable only by the executor; otherwise reverts with NotExecutor
     * @param tokenIn The ERC20 token address to swap from
     * @param tokenInAmount The exact amount of tokenIn to swap
     * @param tokenOut The ERC20 token address to receive
     * @param aggregator The swap aggregator contract to execute the swap
     * @param aggregatorData Calldata to be sent to the aggregator for performing the swap
     * @param poolAddressesProvider The pool addresses provider of the pool, where the debt exists
     * @param maxAllowedSlippageBps Maximum acceptable slippage in basis points (1 bps = 0.01%)
     * @return The amount of tokenOut received from the swap
     */
    function swapAndVerify(
        address tokenIn,
        uint256 tokenInAmount,
        address tokenOut,
        address aggregator,
        bytes memory aggregatorData,
        address poolAddressesProvider,
        uint256 maxAllowedSlippageBps
    ) external returns (uint256);

    /**
     * @notice Repays debt for a given pool with a specified token and amount
     * @param poolAddressesProvider The pool addresses provider of the pool, where the debt exists
     * @param debtToken The address of the token to repay
     * @param amount The amount of the token to repay
     */
    function repayDebt(address poolAddressesProvider, address debtToken, uint256 amount) external;

    /**
     * @notice Deposits collateral for a user into a lending pool
     * @param poolAddressesProvider The pool addresses provider of the pool
     * @param debtToken The address of the collateral token
     * @param amount The amount of collateral to deposit
     */
    function depositCollateral(address poolAddressesProvider, address debtToken, uint256 amount) external;

    /**
     * @notice Allows recovery of ERC20 tokens that may be stuck in the vault back to the user
     * @param token The address of the ERC20 token to recover
     * @param amount The amount of tokens to recover
     */
    function recoverERC20(address token, uint256 amount) external;

    /**
     * @notice Allows recovery of native ETH that may be stuck in the vault back to the user
     * @param amount The amount of ETH to recover
     */
    function recoverETH(uint256 amount) external;
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/**
 * @title IUserVaultFactory
 * @author Neverland
 * @notice Interface for the UserVaultFactory contract.
 *         Allows creation and retrieval of user-specific vaults.
 */
interface IUserVaultFactory {
    /**
     * @notice Emitted when a new user vault is created
     * @param user The user for whom the vault was created
     * @param vault The address of the created vault
     */
    event UserVaultCreated(address indexed user, address indexed vault);

    /*//////////////////////////////////////////////////////////////
                                VIEWS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the vault address for a given user. Creates a new vault if none exists
     * @dev If the vault does not exist, a new BeaconProxy is deployed and initialized for the user
     * @param user The address of the user whose vault is being queried or created
     * @return vault The address of the user's vault
     */
    function getUserVault(address user) external view returns (address vault);

    /*//////////////////////////////////////////////////////////////
                               ACTIONS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the vault address for a given user if it exists
     * @dev If the vault does not exist, returns address(0)
     * @param user The address of the user whose vault is being queried or created
     * @return vault The address of the user's vault
     */
    function getOrCreateUserVault(address user) external returns (address vault);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/**
 * @title IUserVaultRegistry
 * @author Neverland
 * @notice Interface for the UserVaultRegistry contract.
 *         Manages executor and supported aggregators for user vaults.
 */
interface IUserVaultRegistry {
    /**
     * @notice Emitted when the executor is updated
     * @param oldExecutor The previous executor address
     * @param newExecutor The new executor address
     */
    event ExecutorUpdated(address indexed oldExecutor, address indexed newExecutor);

    /**
     * @notice Emitted when an aggregator's support status is updated
     * @param aggregator The aggregator address that was updated
     * @param isActive Whether the aggregator is now supported
     */
    event AggregatorSupportUpdated(address indexed aggregator, bool isActive);

    /**
     * @notice Emitted when the max swap slippage is updated
     * @param oldValue The previous max slippage in bps
     * @param newValue The new max slippage in bps
     */
    event MaxSwapSlippageUpdated(uint256 oldValue, uint256 newValue);

    /*//////////////////////////////////////////////////////////////
                                 VIEWS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Returns the address of the current executor
     * @return The executor address
     */
    function executor() external view returns (address);

    /**
     * @notice Returns the max slippage allowed to be set by executor when swap is made in user vault
     * @return The maximum swap slippage in basis points
     */
    function maxSwapSlippageBps() external view returns (uint256);

    /**
     * @notice Checks if an aggregator is supported
     * @param aggregator The aggregator address to query
     * @return True if supported, false otherwise
     */
    function isSupportedAggregator(address aggregator) external view returns (bool);

    /*//////////////////////////////////////////////////////////////
                                ADMIN
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Sets the executor address
     * @param executor Address of the new executor
     */
    function setExecutor(address executor) external;

    /**
     * @notice Sets the aggregator as supported or not
     * @param aggregator The aggregator address
     * @param isActive True if the aggregator should be supported, false otherwise
     */
    function setSupportedAggregators(address aggregator, bool isActive) external;

    /**
     * @notice Sets the maximum allowed swap slippage, expressed in basis points.
     * @param newMaxSwapSlippageBps The new maximum swap slippage in basis points.
     */
    function setMaxSwapSlippageBps(uint256 newMaxSwapSlippageBps) external;
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/**
 * @title CommonChecksLibrary
 * @author Neverland
 * @notice Shared require/revert helpers for zero/invalid values used across contracts
 */
library CommonChecksLibrary {
    /// @notice Used when a zero address is provided where not allowed.
    error AddressZero();
    /// @notice Used when a zero amount is provided where not allowed.
    error ZeroAmount();
    /// @notice Used when a range is invalid.
    error InvalidRange();
    /// @notice Used when two addresses are the same but must differ.
    error SameAddress();
    /// @notice Used when a balance is zero.
    error ZeroBalance();
    /// @notice Used when a tokenId is invalid.
    error InvalidTokenId();
    /// @notice Used when a from address is invalid.
    error InvalidFromAddress();
    /// @notice Used when a to address is invalid.
    error InvalidToAddress();
    /// @notice Used when a user address is invalid.
    error InvalidUserAddress();
    /// @notice Used a function is called by an account that is not permitted.
    error UnauthorizedAccess();

    /**
     * @notice Reverts if the provided address is zero
     * @param addressToCheck The address to check
     */
    function revertIfZeroAddress(address addressToCheck) internal pure {
        if (addressToCheck == address(0)) revert AddressZero();
    }

    /**
     * @notice Reverts if the provided amount is zero
     * @param amount The amount to check
     */
    function revertIfZeroAmount(uint256 amount) internal pure {
        if (amount == 0) revert ZeroAmount();
    }

    /**
     * @notice Reverts if the [from, to] range is invalid (from > to)
     * @param from The start of the range
     * @param to The end of the range
     */
    function revertIfInvalidRange(uint256 from, uint256 to) internal pure {
        if (from > to) revert InvalidRange();
    }

    /**
     * @notice Reverts if the two addresses are the same
     * @param first The first address to check
     * @param second The second address to check
     */
    function revertIfSameAddress(address first, address second) internal pure {
        if (first == second) revert SameAddress();
    }

    /**
     * @notice Reverts if the balance is zero
     * @param balance The balance to check
     */
    function revertIfZeroBalance(uint256 balance) internal pure {
        if (balance == 0) revert ZeroBalance();
    }

    /**
     * @notice Reverts if the tokenId owner is the zero address
     * @param owner The owner of the tokenId
     */
    function revertIfInvalidTokenId(address owner) internal pure {
        if (owner == address(0)) revert InvalidTokenId();
    }

    /**
     * @notice Reverts if the from address is zero
     * @param from The from address to check
     */
    function revertIfInvalidFromAddress(address from) internal pure {
        if (from == address(0)) revert InvalidFromAddress();
    }

    /**
     * @notice Reverts if the to address is zero
     * @param to The to address to check
     */
    function revertIfInvalidToAddress(address to) internal pure {
        if (to == address(0)) revert InvalidToAddress();
    }

    /**
     * @notice Reverts if the user address is zero
     * @param user The user address to check
     */
    function revertIfInvalidUserAddress(address user) internal pure {
        if (user == address(0)) revert InvalidUserAddress();
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AddressZero","type":"error"},{"inputs":[],"name":"AggregatorNotSupported","type":"error"},{"inputs":[],"name":"ETHSendFailed","type":"error"},{"inputs":[],"name":"GettingAssetPriceFailed","type":"error"},{"inputs":[],"name":"InvalidPoolAddressesProvider","type":"error"},{"inputs":[],"name":"InvalidUserVaultForToken","type":"error"},{"inputs":[],"name":"MaxSlippageTooHigh","type":"error"},{"inputs":[],"name":"NotExecutor","type":"error"},{"inputs":[],"name":"SlippageExceeded","type":"error"},{"inputs":[],"name":"SwapFailed","type":"error"},{"inputs":[],"name":"UnauthorizedAccess","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"userVault","type":"address"},{"indexed":false,"internalType":"address","name":"poolAddressesProvider","type":"address"},{"indexed":false,"internalType":"address","name":"debtToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LoanSelfRepaid","type":"event"},{"inputs":[{"internalType":"address","name":"poolAddressesProvider","type":"address"},{"internalType":"address","name":"debtToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"address","name":"rewardToken","type":"address"}],"name":"getTokenIdsReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"contract IRevenueReward","name":"_revenueReward","type":"address"},{"internalType":"contract IUserVaultRegistry","name":"_userVaultRegistry","type":"address"},{"internalType":"contract IPoolAddressesProviderRegistry","name":"_poolAddressesProviderRegistry","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolAddressesProviderRegistry","outputs":[{"internalType":"contract IPoolAddressesProviderRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recoverERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recoverETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"poolAddressesProvider","type":"address"},{"internalType":"address","name":"debtToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repayDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"debtToken","type":"address"},{"internalType":"address","name":"poolAddressesProvider","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"rewardTokenAmountToSwap","type":"uint256"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"aggregatorData","type":"bytes"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct IUserVault.RepayUserDebtParams","name":"params","type":"tuple"}],"name":"repayUserDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"revenueReward","outputs":[{"internalType":"contract IRevenueReward","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"tokenInAmount","type":"uint256"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"address","name":"aggregator","type":"address"},{"internalType":"bytes","name":"aggregatorData","type":"bytes"},{"internalType":"address","name":"poolAddressesProvider","type":"address"},{"internalType":"uint256","name":"maxAllowedSlippageBps","type":"uint256"}],"name":"swapAndVerify","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"user","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"userVaultRegistry","outputs":[{"internalType":"contract IUserVaultRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

6080604052348015600f57600080fd5b506016601a565b60d7565b600054610100900460ff161560855760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161460d5576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b61217f806100e66000396000f3fe608060405234801561001057600080fd5b50600436106100b45760003560e01c8063d333555311610071578063d33355531461015e578063f2ca6b9114610171578063f5b92c7314610184578063f76aa63f14610197578063f8c8765e146101aa578063f970c3b7146101bd57600080fd5b80630938708b146100b957806325e4be58146100df578063480589d9146100f45780634f8632ba1461011f5780638980f11f14610132578063c26288f614610145575b600080fd5b6100cc6100c7366004611a96565b6101d0565b6040519081526020015b60405180910390f35b6100f26100ed366004611b43565b61044b565b005b600154610107906001600160a01b031681565b6040516001600160a01b0390911681526020016100d6565b600354610107906001600160a01b031681565b6100f2610140366004611b7f565b6105f7565b600054610107906201000090046001600160a01b031681565b6100f261016c366004611bab565b6106c0565b600254610107906001600160a01b031681565b6100f2610192366004611bc4565b6107e3565b6100cc6101a5366004611c05565b610a86565b6100f26101b8366004611cfe565b610d50565b6100f26101cb366004611bc4565b610edf565b600080546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610220573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102449190611d5a565b6001600160a01b03161461026b576040516361968ebb60e11b815260040160405180910390fd5b6102748261111b565b60006102808330611145565b604080516001808252818301909252919250600091906020808301908036833701905050905083816000815181106102ba576102ba611d77565b6001600160a01b0390921660209283029190910190910152845160005b8181101561042257600154875130916001600160a01b03169063ffe436ca908a908590811061030857610308611d77565b60200260200101516040518263ffffffff1660e01b815260040161032e91815260200190565b602060405180830381865afa15801561034b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061036f9190611d5a565b6001600160a01b031614610396576040516389eaac5560e01b815260040160405180910390fd5b60015487516001600160a01b039091169063f5f8d365908990849081106103bf576103bf611d77565b6020026020010151856040518363ffffffff1660e01b81526004016103e5929190611dd2565b600060405180830381600087803b1580156103ff57600080fd5b505af1158015610413573d6000803e3d6000fd5b505050508060010190506102d7565b50600061042f8630611145565b9050600061043d8583611e01565b955050505050505b92915050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa15801561049a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104be9190611d5a565b6001600160a01b0316146104e5576040516361968ebb60e11b815260040160405180910390fd5b6105376104f56040830183611e14565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506100c7925050506080840160608501611e65565b5060006105cb61054d6080840160608501611e65565b608084013561055f6020860186611e65565b61056f60c0870160a08801611e65565b61057c60c0880188611e82565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506105c1925050506040890160208a01611e65565b8860e00135610a86565b90506105f36105e06040840160208501611e65565b6105ed6020850185611e65565b836107e3565b5050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610646573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066a9190611d5a565b6001600160a01b0316148061068957506003546001600160a01b031633145b6106a657604051631a27eac360e11b815260040160405180910390fd5b6003546105f3906001600160a01b038481169116836111ba565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa15801561070f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107339190611d5a565b6001600160a01b0316148061075257506003546001600160a01b031633145b61076f57604051631a27eac360e11b815260040160405180910390fd5b6003546040516000916001600160a01b03169083908381818185875af1925050503d80600081146107bc576040519150601f19603f3d011682016040523d82523d6000602084013e6107c1565b606091505b50509050806105f35760405163cef4eed760e01b815260040160405180910390fd5b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610832573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108569190611d5a565b6001600160a01b03161461087d576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa1580156108cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108ef9190611ec9565b905080600003610912576040516343062b1560e11b815260040160405180910390fd5b6000856001600160a01b031663026b1d5f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610952573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109769190611d5a565b905061098c6001600160a01b0386168286611222565b60035460405163573ade8160e01b81526001600160a01b038781166004830152602482018790526002604483015291821660648201529082169063573ade81906084016020604051808303816000875af11580156109ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a129190611ec9565b50610a286001600160a01b038616826000611222565b600354604080516001600160a01b0389811682528881166020830152918101879052309291909116907f067cfc02bbdb52c93d03426f2556521981a721c70c3f04a23062fc6678c5dbae9060600160405180910390a3505050505050565b600080546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610ad6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610afa9190611d5a565b6001600160a01b031614610b21576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611ec9565b905080600003610bb6576040516343062b1560e11b815260040160405180910390fd5b610bbf8a61111b565b610bc88861111b565b610bd189611337565b610bda8761111b565b600060029054906101000a90046001600160a01b03166001600160a01b031663b7c3565d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c519190611ec9565b841115610c7157604051636dabd5db60e01b815260040160405180910390fd5b6000610c808b8b8b8b8b611358565b90506000610c8f8c8b896114ca565b9050600281511080610cbb575080600081518110610caf57610caf611d77565b60200260200101516000145b80610ce0575080600181518110610cd457610cd4611d77565b60200260200101516000145b15610cfe5760405163283c2ce760e11b815260040160405180910390fd5b610d418c8c83600081518110610d1657610d16611d77565b60200260200101518d8686600181518110610d3357610d33611d77565b60200260200101518c611632565b509a9950505050505050505050565b600054610100900460ff1615808015610d705750600054600160ff909116105b80610d8a5750303b158015610d8a575060005460ff166001145b610df25760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff191660011790558015610e15576000805461ff0019166101001790555b610e1e8361111b565b610e278261111b565b610e308461111b565b610e398561111b565b600380546001600160a01b03199081166001600160a01b03888116919091179092556001805482168784161790556000805462010000600160b01b0319166201000087851602179055600280549091169184169190911790558015610ed8576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050505050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190611d5a565b6001600160a01b031614610f79576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa158015610fc7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610feb9190611ec9565b90508060000361100e576040516343062b1560e11b815260040160405180910390fd5b6000856001600160a01b031663026b1d5f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561104e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110729190611d5a565b90506110886001600160a01b0386168286611222565b60035460405163617ba03760e01b81526001600160a01b038781166004830152602482018790529182166044820152600060648201529082169063617ba03790608401600060405180830381600087803b1580156110e557600080fd5b505af11580156110f9573d6000803e3d6000fd5b50611113925050506001600160a01b038616826000611222565b505050505050565b6001600160a01b03811661114257604051639fabe1c160e01b815260040160405180910390fd5b50565b6040516370a0823160e01b81526001600160a01b038281166004830152600091908416906370a0823190602401602060405180830381865afa15801561118f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b39190611ec9565b9392505050565b6040516001600160a01b03831660248201526044810182905261121d90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526117a1565b505050565b80158061129c5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015611276573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061129a9190611ec9565b155b6113075760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610de9565b6040516001600160a01b03831660248201526044810182905261121d90849063095ea7b360e01b906064016111e6565b8060000361114257604051631f2a200560e01b815260040160405180910390fd5b6000806113658530611145565b60005460405163ee79a6e160e01b81526001600160a01b038781166004830152929350620100009091049091169063ee79a6e190602401602060405180830381865afa1580156113b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113dd9190611ee2565b6113fa57604051631c9eb17560e11b815260040160405180910390fd5b61140e6001600160a01b0388168588611222565b6000846001600160a01b0316846040516114289190611f28565b6000604051808303816000865af19150503d8060008114611465576040519150601f19603f3d011682016040523d82523d6000602084013e61146a565b606091505b505090508061148c5760405163081ceff360e41b815260040160405180910390fd5b60006114988730611145565b905060006114a68483611e01565b90506114bd6001600160a01b038b16886000611222565b9998505050505050505050565b60408051600280825260608083018452926000929190602083019080368337019050509050848160008151811061150357611503611d77565b60200260200101906001600160a01b031690816001600160a01b031681525050838160018151811061153757611537611d77565b60200260200101906001600160a01b031690816001600160a01b031681525050826001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611595573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115b99190611d5a565b6001600160a01b0316639d23d9f2826040518263ffffffff1660e01b81526004016115e49190611f44565b600060405180830381865afa158015611601573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526116299190810190611f57565b95945050505050565b6000876001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611672573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116969190611fed565b90506000856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116fc9190611fed565b9050600061170b83600a6120f7565b611715898b612106565b61171f919061211d565b9050600061172e83600a6120f7565b6117388789612106565b611742919061211d565b905081811015611794576000826117598382611e01565b61176590612710612106565b61176f919061211d565b90508581111561179257604051638199f5f360e01b815260040160405180910390fd5b505b5050505050505050505050565b60006117f6826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166118769092919063ffffffff16565b90508051600014806118175750808060200190518101906118179190611ee2565b61121d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610de9565b6060611885848460008561188d565b949350505050565b6060824710156118ee5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610de9565b600080866001600160a01b0316858760405161190a9190611f28565b60006040518083038185875af1925050503d8060008114611947576040519150601f19603f3d011682016040523d82523d6000602084013e61194c565b606091505b509150915061195d87838387611968565b979650505050505050565b606083156119d75782516000036119d0576001600160a01b0385163b6119d05760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610de9565b5081611885565b61188583838151156119ec5781518083602001fd5b8060405162461bcd60e51b8152600401610de9919061213f565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611a4557611a45611a06565b604052919050565b600067ffffffffffffffff821115611a6757611a67611a06565b5060051b60200190565b6001600160a01b038116811461114257600080fd5b8035611a9181611a71565b919050565b60008060408385031215611aa957600080fd5b823567ffffffffffffffff811115611ac057600080fd5b8301601f81018513611ad157600080fd5b8035611ae4611adf82611a4d565b611a1c565b8082825260208201915060208360051b850101925087831115611b0657600080fd5b6020840193505b82841015611b28578335825260209384019390910190611b0d565b9450611b3a9250505060208401611a86565b90509250929050565b600060208284031215611b5557600080fd5b813567ffffffffffffffff811115611b6c57600080fd5b820161010081850312156111b357600080fd5b60008060408385031215611b9257600080fd5b8235611b9d81611a71565b946020939093013593505050565b600060208284031215611bbd57600080fd5b5035919050565b600080600060608486031215611bd957600080fd5b8335611be481611a71565b92506020840135611bf481611a71565b929592945050506040919091013590565b600080600080600080600060e0888a031215611c2057600080fd5b8735611c2b81611a71565b9650602088013595506040880135611c4281611a71565b94506060880135611c5281611a71565b9350608088013567ffffffffffffffff811115611c6e57600080fd5b8801601f81018a13611c7f57600080fd5b803567ffffffffffffffff811115611c9957611c99611a06565b611cac601f8201601f1916602001611a1c565b8181528b6020838501011115611cc157600080fd5b81602084016020830137600060208383010152809550505050611ce660a08901611a86565b96999598509396929591949193505060c09091013590565b60008060008060808587031215611d1457600080fd5b8435611d1f81611a71565b93506020850135611d2f81611a71565b92506040850135611d3f81611a71565b91506060850135611d4f81611a71565b939692955090935050565b600060208284031215611d6c57600080fd5b81516111b381611a71565b634e487b7160e01b600052603260045260246000fd5b600081518084526020840193506020830160005b82811015611dc85781516001600160a01b0316865260209586019590910190600101611da1565b5093949350505050565b8281526040602082015260006118856040830184611d8d565b634e487b7160e01b600052601160045260246000fd5b8181038181111561044557610445611deb565b6000808335601e19843603018112611e2b57600080fd5b83018035915067ffffffffffffffff821115611e4657600080fd5b6020019150600581901b3603821315611e5e57600080fd5b9250929050565b600060208284031215611e7757600080fd5b81356111b381611a71565b6000808335601e19843603018112611e9957600080fd5b83018035915067ffffffffffffffff821115611eb457600080fd5b602001915036819003821315611e5e57600080fd5b600060208284031215611edb57600080fd5b5051919050565b600060208284031215611ef457600080fd5b815180151581146111b357600080fd5b60005b83811015611f1f578181015183820152602001611f07565b50506000910152565b60008251611f3a818460208701611f04565b9190910192915050565b6020815260006111b36020830184611d8d565b600060208284031215611f6957600080fd5b815167ffffffffffffffff811115611f8057600080fd5b8201601f81018413611f9157600080fd5b8051611f9f611adf82611a4d565b8082825260208201915060208360051b850101925086831115611fc157600080fd5b6020840193505b82841015611fe3578351825260209384019390910190611fc8565b9695505050505050565b600060208284031215611fff57600080fd5b815160ff811681146111b357600080fd5b6001815b600184111561204b5780850481111561202f5761202f611deb565b600184161561203d57908102905b60019390931c928002612014565b935093915050565b60008261206257506001610445565b8161206f57506000610445565b8160018114612085576002811461208f576120ab565b6001915050610445565b60ff8411156120a0576120a0611deb565b50506001821b610445565b5060208310610133831016604e8410600b84101617156120ce575081810a610445565b6120db6000198484612010565b80600019048211156120ef576120ef611deb565b029392505050565b60006111b360ff841683612053565b808202811582820484141761044557610445611deb565b60008261213a57634e487b7160e01b600052601260045260246000fd5b500490565b602081526000825180602084015261215e816040850160208701611f04565b601f01601f1916919091016040019291505056fea164736f6c634300081e000a

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100b45760003560e01c8063d333555311610071578063d33355531461015e578063f2ca6b9114610171578063f5b92c7314610184578063f76aa63f14610197578063f8c8765e146101aa578063f970c3b7146101bd57600080fd5b80630938708b146100b957806325e4be58146100df578063480589d9146100f45780634f8632ba1461011f5780638980f11f14610132578063c26288f614610145575b600080fd5b6100cc6100c7366004611a96565b6101d0565b6040519081526020015b60405180910390f35b6100f26100ed366004611b43565b61044b565b005b600154610107906001600160a01b031681565b6040516001600160a01b0390911681526020016100d6565b600354610107906001600160a01b031681565b6100f2610140366004611b7f565b6105f7565b600054610107906201000090046001600160a01b031681565b6100f261016c366004611bab565b6106c0565b600254610107906001600160a01b031681565b6100f2610192366004611bc4565b6107e3565b6100cc6101a5366004611c05565b610a86565b6100f26101b8366004611cfe565b610d50565b6100f26101cb366004611bc4565b610edf565b600080546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610220573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102449190611d5a565b6001600160a01b03161461026b576040516361968ebb60e11b815260040160405180910390fd5b6102748261111b565b60006102808330611145565b604080516001808252818301909252919250600091906020808301908036833701905050905083816000815181106102ba576102ba611d77565b6001600160a01b0390921660209283029190910190910152845160005b8181101561042257600154875130916001600160a01b03169063ffe436ca908a908590811061030857610308611d77565b60200260200101516040518263ffffffff1660e01b815260040161032e91815260200190565b602060405180830381865afa15801561034b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061036f9190611d5a565b6001600160a01b031614610396576040516389eaac5560e01b815260040160405180910390fd5b60015487516001600160a01b039091169063f5f8d365908990849081106103bf576103bf611d77565b6020026020010151856040518363ffffffff1660e01b81526004016103e5929190611dd2565b600060405180830381600087803b1580156103ff57600080fd5b505af1158015610413573d6000803e3d6000fd5b505050508060010190506102d7565b50600061042f8630611145565b9050600061043d8583611e01565b955050505050505b92915050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa15801561049a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104be9190611d5a565b6001600160a01b0316146104e5576040516361968ebb60e11b815260040160405180910390fd5b6105376104f56040830183611e14565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506100c7925050506080840160608501611e65565b5060006105cb61054d6080840160608501611e65565b608084013561055f6020860186611e65565b61056f60c0870160a08801611e65565b61057c60c0880188611e82565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506105c1925050506040890160208a01611e65565b8860e00135610a86565b90506105f36105e06040840160208501611e65565b6105ed6020850185611e65565b836107e3565b5050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610646573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066a9190611d5a565b6001600160a01b0316148061068957506003546001600160a01b031633145b6106a657604051631a27eac360e11b815260040160405180910390fd5b6003546105f3906001600160a01b038481169116836111ba565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa15801561070f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107339190611d5a565b6001600160a01b0316148061075257506003546001600160a01b031633145b61076f57604051631a27eac360e11b815260040160405180910390fd5b6003546040516000916001600160a01b03169083908381818185875af1925050503d80600081146107bc576040519150601f19603f3d011682016040523d82523d6000602084013e6107c1565b606091505b50509050806105f35760405163cef4eed760e01b815260040160405180910390fd5b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610832573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108569190611d5a565b6001600160a01b03161461087d576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa1580156108cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108ef9190611ec9565b905080600003610912576040516343062b1560e11b815260040160405180910390fd5b6000856001600160a01b031663026b1d5f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610952573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109769190611d5a565b905061098c6001600160a01b0386168286611222565b60035460405163573ade8160e01b81526001600160a01b038781166004830152602482018790526002604483015291821660648201529082169063573ade81906084016020604051808303816000875af11580156109ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a129190611ec9565b50610a286001600160a01b038616826000611222565b600354604080516001600160a01b0389811682528881166020830152918101879052309291909116907f067cfc02bbdb52c93d03426f2556521981a721c70c3f04a23062fc6678c5dbae9060600160405180910390a3505050505050565b600080546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610ad6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610afa9190611d5a565b6001600160a01b031614610b21576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611ec9565b905080600003610bb6576040516343062b1560e11b815260040160405180910390fd5b610bbf8a61111b565b610bc88861111b565b610bd189611337565b610bda8761111b565b600060029054906101000a90046001600160a01b03166001600160a01b031663b7c3565d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c519190611ec9565b841115610c7157604051636dabd5db60e01b815260040160405180910390fd5b6000610c808b8b8b8b8b611358565b90506000610c8f8c8b896114ca565b9050600281511080610cbb575080600081518110610caf57610caf611d77565b60200260200101516000145b80610ce0575080600181518110610cd457610cd4611d77565b60200260200101516000145b15610cfe5760405163283c2ce760e11b815260040160405180910390fd5b610d418c8c83600081518110610d1657610d16611d77565b60200260200101518d8686600181518110610d3357610d33611d77565b60200260200101518c611632565b509a9950505050505050505050565b600054610100900460ff1615808015610d705750600054600160ff909116105b80610d8a5750303b158015610d8a575060005460ff166001145b610df25760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff191660011790558015610e15576000805461ff0019166101001790555b610e1e8361111b565b610e278261111b565b610e308461111b565b610e398561111b565b600380546001600160a01b03199081166001600160a01b03888116919091179092556001805482168784161790556000805462010000600160b01b0319166201000087851602179055600280549091169184169190911790558015610ed8576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050505050565b6000546040805163c34c08e560e01b8152905133926201000090046001600160a01b03169163c34c08e59160048083019260209291908290030181865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190611d5a565b6001600160a01b031614610f79576040516361968ebb60e11b815260040160405180910390fd5b60025460405163d0267be760e01b81526001600160a01b038086166004830152859260009291169063d0267be790602401602060405180830381865afa158015610fc7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610feb9190611ec9565b90508060000361100e576040516343062b1560e11b815260040160405180910390fd5b6000856001600160a01b031663026b1d5f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561104e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110729190611d5a565b90506110886001600160a01b0386168286611222565b60035460405163617ba03760e01b81526001600160a01b038781166004830152602482018790529182166044820152600060648201529082169063617ba03790608401600060405180830381600087803b1580156110e557600080fd5b505af11580156110f9573d6000803e3d6000fd5b50611113925050506001600160a01b038616826000611222565b505050505050565b6001600160a01b03811661114257604051639fabe1c160e01b815260040160405180910390fd5b50565b6040516370a0823160e01b81526001600160a01b038281166004830152600091908416906370a0823190602401602060405180830381865afa15801561118f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b39190611ec9565b9392505050565b6040516001600160a01b03831660248201526044810182905261121d90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526117a1565b505050565b80158061129c5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015611276573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061129a9190611ec9565b155b6113075760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610de9565b6040516001600160a01b03831660248201526044810182905261121d90849063095ea7b360e01b906064016111e6565b8060000361114257604051631f2a200560e01b815260040160405180910390fd5b6000806113658530611145565b60005460405163ee79a6e160e01b81526001600160a01b038781166004830152929350620100009091049091169063ee79a6e190602401602060405180830381865afa1580156113b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113dd9190611ee2565b6113fa57604051631c9eb17560e11b815260040160405180910390fd5b61140e6001600160a01b0388168588611222565b6000846001600160a01b0316846040516114289190611f28565b6000604051808303816000865af19150503d8060008114611465576040519150601f19603f3d011682016040523d82523d6000602084013e61146a565b606091505b505090508061148c5760405163081ceff360e41b815260040160405180910390fd5b60006114988730611145565b905060006114a68483611e01565b90506114bd6001600160a01b038b16886000611222565b9998505050505050505050565b60408051600280825260608083018452926000929190602083019080368337019050509050848160008151811061150357611503611d77565b60200260200101906001600160a01b031690816001600160a01b031681525050838160018151811061153757611537611d77565b60200260200101906001600160a01b031690816001600160a01b031681525050826001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611595573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115b99190611d5a565b6001600160a01b0316639d23d9f2826040518263ffffffff1660e01b81526004016115e49190611f44565b600060405180830381865afa158015611601573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526116299190810190611f57565b95945050505050565b6000876001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611672573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116969190611fed565b90506000856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116fc9190611fed565b9050600061170b83600a6120f7565b611715898b612106565b61171f919061211d565b9050600061172e83600a6120f7565b6117388789612106565b611742919061211d565b905081811015611794576000826117598382611e01565b61176590612710612106565b61176f919061211d565b90508581111561179257604051638199f5f360e01b815260040160405180910390fd5b505b5050505050505050505050565b60006117f6826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166118769092919063ffffffff16565b90508051600014806118175750808060200190518101906118179190611ee2565b61121d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610de9565b6060611885848460008561188d565b949350505050565b6060824710156118ee5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610de9565b600080866001600160a01b0316858760405161190a9190611f28565b60006040518083038185875af1925050503d8060008114611947576040519150601f19603f3d011682016040523d82523d6000602084013e61194c565b606091505b509150915061195d87838387611968565b979650505050505050565b606083156119d75782516000036119d0576001600160a01b0385163b6119d05760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610de9565b5081611885565b61188583838151156119ec5781518083602001fd5b8060405162461bcd60e51b8152600401610de9919061213f565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611a4557611a45611a06565b604052919050565b600067ffffffffffffffff821115611a6757611a67611a06565b5060051b60200190565b6001600160a01b038116811461114257600080fd5b8035611a9181611a71565b919050565b60008060408385031215611aa957600080fd5b823567ffffffffffffffff811115611ac057600080fd5b8301601f81018513611ad157600080fd5b8035611ae4611adf82611a4d565b611a1c565b8082825260208201915060208360051b850101925087831115611b0657600080fd5b6020840193505b82841015611b28578335825260209384019390910190611b0d565b9450611b3a9250505060208401611a86565b90509250929050565b600060208284031215611b5557600080fd5b813567ffffffffffffffff811115611b6c57600080fd5b820161010081850312156111b357600080fd5b60008060408385031215611b9257600080fd5b8235611b9d81611a71565b946020939093013593505050565b600060208284031215611bbd57600080fd5b5035919050565b600080600060608486031215611bd957600080fd5b8335611be481611a71565b92506020840135611bf481611a71565b929592945050506040919091013590565b600080600080600080600060e0888a031215611c2057600080fd5b8735611c2b81611a71565b9650602088013595506040880135611c4281611a71565b94506060880135611c5281611a71565b9350608088013567ffffffffffffffff811115611c6e57600080fd5b8801601f81018a13611c7f57600080fd5b803567ffffffffffffffff811115611c9957611c99611a06565b611cac601f8201601f1916602001611a1c565b8181528b6020838501011115611cc157600080fd5b81602084016020830137600060208383010152809550505050611ce660a08901611a86565b96999598509396929591949193505060c09091013590565b60008060008060808587031215611d1457600080fd5b8435611d1f81611a71565b93506020850135611d2f81611a71565b92506040850135611d3f81611a71565b91506060850135611d4f81611a71565b939692955090935050565b600060208284031215611d6c57600080fd5b81516111b381611a71565b634e487b7160e01b600052603260045260246000fd5b600081518084526020840193506020830160005b82811015611dc85781516001600160a01b0316865260209586019590910190600101611da1565b5093949350505050565b8281526040602082015260006118856040830184611d8d565b634e487b7160e01b600052601160045260246000fd5b8181038181111561044557610445611deb565b6000808335601e19843603018112611e2b57600080fd5b83018035915067ffffffffffffffff821115611e4657600080fd5b6020019150600581901b3603821315611e5e57600080fd5b9250929050565b600060208284031215611e7757600080fd5b81356111b381611a71565b6000808335601e19843603018112611e9957600080fd5b83018035915067ffffffffffffffff821115611eb457600080fd5b602001915036819003821315611e5e57600080fd5b600060208284031215611edb57600080fd5b5051919050565b600060208284031215611ef457600080fd5b815180151581146111b357600080fd5b60005b83811015611f1f578181015183820152602001611f07565b50506000910152565b60008251611f3a818460208701611f04565b9190910192915050565b6020815260006111b36020830184611d8d565b600060208284031215611f6957600080fd5b815167ffffffffffffffff811115611f8057600080fd5b8201601f81018413611f9157600080fd5b8051611f9f611adf82611a4d565b8082825260208201915060208360051b850101925086831115611fc157600080fd5b6020840193505b82841015611fe3578351825260209384019390910190611fc8565b9695505050505050565b600060208284031215611fff57600080fd5b815160ff811681146111b357600080fd5b6001815b600184111561204b5780850481111561202f5761202f611deb565b600184161561203d57908102905b60019390931c928002612014565b935093915050565b60008261206257506001610445565b8161206f57506000610445565b8160018114612085576002811461208f576120ab565b6001915050610445565b60ff8411156120a0576120a0611deb565b50506001821b610445565b5060208310610133831016604e8410600b84101617156120ce575081810a610445565b6120db6000198484612010565b80600019048211156120ef576120ef611deb565b029392505050565b60006111b360ff841683612053565b808202811582820484141761044557610445611deb565b60008261213a57634e487b7160e01b600052601260045260246000fd5b500490565b602081526000825180602084015261215e816040850160208701611f04565b601f01601f1916919091016040019291505056fea164736f6c634300081e000a

Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

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.