// Contract: ConvexCurveLPVault2
// Target function: function _claimRewards(
 * - Caller is anyone
   */
  function processYield() external virtual;

  /**
   * @dev Get price per share based on yield strategy
   * @return The value of price per share
   */
  function pricePerShare() external view virtual returns (uint256);

  /**
   * @dev Get vault Yield per year with wad decimal(=18)
   * @return The vault yield value per year
   */
  function vaultYieldInPrice() external view virtual returns (uint256) {
    return 0;
  }

  /**
   * @dev Set treasury address and vault fee
   * - Caller is only PoolAdmin which is set on LendingPoolAddressesProvider contract
   * @param _treasury The treasury address
   * @param _fee The vault fee which has more two decimals, ex: 100% = 100_00
   */
  function setTreasuryInfo(address _treasury, uint256 _fee) external payable onlyAdmin {
    require(_treasury != address(0), Errors.VT_TREASURY_INVALID);
    require(_fee <= 30_00, Errors.VT_FEE_TOO_BIG);
    _treasuryAddress = _treasury;
    _vaultFee = _fee;

    emit SetTreasuryInfo(_treasury, _fee);
  }

  /**
   * @dev deposit collateral asset to lending pool
   * @param _asset The address of collateral external asset
   * @param _amount Collateral external asset amount
   * @param _user The address of user
   */
  function _deposit(
    address _asset,
    uint256 _amount,
    address _user
  ) internal {
    if (_asset != address(0)) {
      // asset = ERC20
      require(msg.value == 0, Errors.VT_COLLATERAL_DEPOSIT_INVALID);
    } else {
      // asset = ETH
      require(msg.value == _amount, Errors.VT_COLLATERAL_DEPOSIT_REQUIRE_ETH);
    }
    // Deposit asset to vault and receive stAsset
    // Ex: if user deposit 100ETH, this will deposit 100ETH to Lido and receive 100stETH
    (address _stAsset, uint256 _stAssetAmount) = _depositToYieldPool(_asset, _amount);

    // Deposit stAsset to lendingPool, then user will get aToken of stAsset
    ILendingPool(_addressesProvider.getLendingPool()).deposit(_stAsset, _stAssetAmount, _user, 0);

    emit DepositCollateral(_asset, _user, _amount);
  }

  /**
   * @dev Get yield based on strategy and re-deposit
   * @param _stAsset The address of collateral internal asset
   * @return yield amount of collateral internal asset
   */
  function _getYield(address _stAsset) internal returns (uint256) {
    uint256 yieldStAsset = _getYieldAmount(_stAsset);
    require(yieldStAsset != 0, Errors.VT_PROCESS_YIELD_INVALID);

    ILendingPool(_addressesProvider.getLendingPool()).getYield(_stAsset, yieldStAsset);
    return yieldStAsset;
  }

  /**
   * @dev Get yield amount based on strategy
   * @param _stAsset The address of collateral internal asset
   * @return yield amount of collateral internal asset
   */
  function _getYieldAmount(address _stAsset) internal view returns (uint256) {
    (uint256 stAssetBalance, uint256 aTokenBalance) = ILendingPool(
      _addressesProvider.getLendingPool()
    ).getTotalBalanceOfAssetPair(_stAsset);

    // when deposit for collateral, stAssetBalance = aTokenBalance
    // But stAssetBalance should increase overtime, so vault can grab yield from lendingPool.
    // yield = stAssetBalance - aTokenBalance
    if (stAssetBalance > aTokenBalance) return stAssetBalance - aTokenBalance;

    return 0;
  }

  /**
   * @dev Deposit collateral external asset to yield pool based on strategy and receive collateral internal asset
   * @param _asset The address of collateral external asset
   * @param _amount The amount of collateral external asset
   * @return The address of collateral internal asset
   * @return The amount of collateral internal asset
   */
  function _depositToYieldPool(address _asset, uint256 _amount)
    internal
    virtual
    returns (address, uint256);

  /**
   * @dev Withdraw collateral internal asset from yield pool based on strategy and deliver collateral external asset
   * @param _asset The address of collateral external asset
   * @param _amount The withdrawal amount of collateral internal asset
   * @param _to The address of receiving collateral external asset
   * @return The amount of collateral external asset
   */
  function _withdrawFromYieldPool(
    address _asset,
    uint256 _amount,
    address _to
  ) internal virtual returns (uint256);

  /**
   * @dev Get Withdrawal amount of collateral internal asset based on strategy
   * @param _asset The address of collateral external asset
   * @param _amount The withdrawal amount of collateral external asset
   * @return The address of collateral internal asset
   * @return The withdrawal amount of collateral internal asset
   */
  function _getWithdrawalAmount(address _asset, uint256 _amount)
    internal
    view
    virtual
    returns (address, uint256);
}

library SafeERC20 {
  using Address for address;

  function safeTransfer(
    IERC20 token,
    address to,
    uint256 value
  ) internal {
    callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
  }

  function safeTransferFrom(
    IERC20 token,
    address from,
    address to,
    uint256 value
  ) internal {
    callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
  }

  function safeApprove(
    IERC20 token,
    address spender,
    uint256 value
  ) internal {
    require(
      (value == 0) || (token.allowance(address(this), spender) == 0),
      'SafeERC20: approve from non-zero to non-zero allowance'
    );
    callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
  }

  function callOptionalReturn(IERC20 token, bytes memory data) private {
    require(address(token).isContract(), 'SafeERC20: call to non-contract');

    // solhint-disable-next-line avoid-low-level-calls
    (bool success, bytes memory returndata) = address(token).call(data);
    require(success, 'SafeERC20: low-level call failed');

    if (returndata.length != 0) {
      // Return data is optional
      // solhint-disable-next-line max-line-length
      require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
    }
  }
}

interface IScaledBalanceToken {
  /**
   * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
   * updated stored balance divided by the reserve's liquidity index at the moment of the update
   * @param user The user whose balance is calculated
   * @return The scaled balance of the user
   **/
  function scaledBalanceOf(address user) external view returns (uint256);

  /**
   * @dev Returns the scaled balance of the user and the scaled total supply.
   * @param user The address of the user
   * @return The scaled balance of the user
   * @return The scaled balance and the scaled total supply
   **/
  function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);

  /**
   * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
   * @return The scaled total supply
   **/
  function scaledTotalSupply() external view returns (uint256);
}

struct UserData {
  uint256 index;
  uint256 expectedRewards;
  uint256 claimableRewards;
}

struct AssetData {
  uint256 index;
  uint256 lastAvailableRewards;
  address rewardToken; // The address of reward token
  address yieldAddress; // The address of vault
  mapping(address => UserData) users;
  uint256 claimableIndex;
}

struct AggregatedRewardsData {
  address asset;
  address rewardToken;
  uint256 balance;
}

abstract contract IncentiveVault is GeneralVault {
  using SafeERC20 for IERC20;

  /**
   * @dev Emitted on setIncentiveRatio()
   * @param ratio The incentive ratio value, 1% = 100
   **/
  event SetIncentiveRatio(uint256 ratio);

  /**
   * @dev Get the incentive token address supported on this vault
   * @return The address of incentive token
   */
  function getIncentiveToken() public view virtual returns (address);

  /**
   * @dev Get current total incentive amount
   * @return The total amount of incentive token
   */
  function getCurrentTotalIncentiveAmount() external view virtual returns (uint256);

  /**
   * @dev Get Incentive Ratio
   * @return The incentive ratio value
   */
  function getIncentiveRatio() external view virtual returns (uint256);

  /**
   * @dev Set Incentive Ratio
   * - Caller is only PoolAdmin which is set on LendingPoolAddressesProvider contract
   */
  function setIncentiveRatio(uint256 _ratio) external virtual;

  /**
   * @dev Get AToken address for the vault
   * @return The AToken address for the vault
   */
  function _getAToken() internal view virtual returns (address);

  /**
   * @dev Claim all rewards and send some to YieldDistributor
   */
  function _clearRewards() internal virtual;

  /**
   * @dev Send incentive to YieldDistribution
   * @param amount The amount of incentive token
   */
  function _sendIncentive(uint256 amount) internal {
    address asset = _getAToken();
    address incentiveToken = getIncentiveToken();

    // transfer to YieldDistributor
    address yieldDistributor = _addressesProvider.getAddress('VR_YIELD_DISTRIBUTOR');
    IERC20(incentiveToken).safeTransfer(yieldDistributor, amount);

    // notify to YieldDistributor so that it updates asset index
    VariableYieldDistribution(yieldDistributor).receivedRewards(asset, incentiveToken, amount);
  }
}

library Math {
  /**
   * @dev Returns the largest of two numbers.
   */
  function max(uint256 a, uint256 b) internal pure returns (uint256) {
    return a >= b ? a : b;
  }

  /**
   * @dev Returns the smallest of two numbers.
   */
  function min(uint256 a, uint256 b) internal pure returns (uint256) {
    return a < b ? a : b;
  }

  /**
   * @dev Returns the average of two numbers. The result is rounded towards
   * zero.
   */
  function average(uint256 a, uint256 b) internal pure returns (uint256) {
    // (a + b) / 2 can overflow.
    return (a & b) + (a ^ b) / 2;
  }

  /**
   * @dev Returns the ceiling of the division of two numbers.
   *
   * This differs from standard division with `/` in that it rounds up instead
   * of rounding down.
   */
  function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
    // (a + b - 1) / b can overflow on addition, so we distribute.
    return a / b + (a % b == 0 ? 0 : 1);
  }
}

contract VariableYieldDistribution is VersionedInitializable {
  using SafeERC20 for IERC20;

  uint256 private constant REVISION = 1;
  uint8 private constant PRECISION = 27;
  address public immutable EMISSION_MANAGER;

  ILendingPoolAddressesProvider internal _addressProvider;

  mapping(address => AssetData) public assets;

  event AssetRegistered(address indexed asset, address indexed yieldAddress);
  event AssetIndexUpdated(address indexed asset, uint256 index, uint256 rewardsAmount);
  event UserIndexUpdated(
    address indexed user,
    address indexed asset,
    uint256 index,
    uint256 expectedRewardsAmount
  );
  event RewardsReceived(address indexed asset, address indexed rewardToken, uint256 receivedAmount);
  event RewardsAccrued(address indexed user, address indexed asset, uint256 amount);
  event RewardsClaimed(
    address indexed asset,
    address indexed user,
    address indexed to,
    uint256 amount
  );

  modifier onlyEmissionManager() {
    require(msg.sender == EMISSION_MANAGER, Errors.CALLER_NOT_EMISSION_MANAGER);
    _;
  }

  modifier onlyIncentiveController() {
    require(
      msg.sender == _addressProvider.getIncentiveController(),
      Errors.CALLER_NOT_INCENTIVE_CONTROLLER
    );
    _;
  }

  constructor(address emissionManager) {
    EMISSION_MANAGER = emissionManager;
  }

  /**
   * @dev Initialize IStakedTokenIncentivesController
   * @param _provider the address of the corresponding addresses provider
   **/
  function initialize(ILendingPoolAddressesProvider _provider) external initializer {
    _addressProvider = _provider;
  }

  /**
   * @dev Register an asset with vault which will keep some of yield for borrowers
   * @param asset The address of the reference asset
   * @param yieldAddress The address of the vault
   */
  function registerAsset(address asset, address yieldAddress) external payable onlyEmissionManager {
    AssetData storage assetData = assets[asset];
    address rewardToken = IncentiveVault(yieldAddress).getIncentiveToken();

    require(assetData.yieldAddress == address(0), Errors.YD_VR_ASSET_ALREADY_IN_USE);
    require(rewardToken != address(0), Errors.YD_VR_INVALID_VAULT);

    uint256 totalStaked = IScaledBalanceToken(asset).scaledTotalSupply();
    assetData.yieldAddress = yieldAddress;
    assetData.rewardToken = rewardToken;

    (uint256 lastAvailableRewards, uint256 increasedRewards) = _getAvailableRewardsAmount(
      assetData
    );

    _updateAssetStateInternal(
      asset,
      assetData,
      totalStaked,
      lastAvailableRewards,
      increasedRewards
    );

    emit AssetRegistered(asset, yieldAddress);
  }

  function receivedRewards(
    address asset,
    address rewardToken,
    uint256 amount
  ) external {
    AssetData storage assetData = assets[asset];
    address _rewardToken = assetData.rewardToken;
    address _yieldAddress = assetData.yieldAddress;
    uint256 lastAvailableRewards = assetData.lastAvailableRewards;

    require(msg.sender == _yieldAddress, Errors.YD_VR_CALLER_NOT_VAULT);
    require(_rewardToken != address(0), Errors.YD_VR_ASSET_NOT_REGISTERED);
    require(rewardToken == _rewardToken, Errors.YD_VR_REWARD_TOKEN_NOT_VALID);
    require(amount >= lastAvailableRewards, Errors.YD_VR_INVALID_REWARDS_AMOUNT);

    uint256 increasedRewards = amount - lastAvailableRewards;
    uint256 totalStaked = IScaledBalanceToken(asset).scaledTotalSupply();

    _updateAssetStateInternal(asset, assetData, totalStaked, 0, increasedRewards);

    emit RewardsReceived(asset, rewardToken, amount);
  }

  function handleAction(
    address user,
    address asset,
    uint256 totalSupply,
    uint256 userBalance
  ) external payable onlyIncentiveController {
    uint256 accruedRewards = _updateUserAssetInternal(user, asset, userBalance, totalSupply);
    if (accruedRewards != 0) {
      emit RewardsAccrued(user, asset, accruedRewards);
    }
  }

  function getRewardsBalance(address[] calldata _assets, address _user)
    external
    view
    returns (AggregatedRewardsData[] memory)
  {
    uint256 length = _assets.length;
    AggregatedRewardsData[] memory rewards = new AggregatedRewardsData[](length);

    for (uint256 i; i < length; ++i) {
      (uint256 stakedByUser, ) = IScaledBalanceToken(_assets[i]).getScaledUserBalanceAndSupply(
        _user
      );
      rewards[i].asset = _assets[i];
      (rewards[i].rewardToken, rewards[i].balance) = _getUnclaimedRewards(
        _user,
        _assets[i],
        stakedByUser
      );
    }

    return rewards;
  }

  function claimRewards(
    address[] calldata _assets,
    uint256[] calldata _amounts,
    address _to
  ) external returns (uint256) {
    require(_to != address(0), 'INVALID_TO_ADDRESS');
    require(_assets.length == _amounts.length, Errors.YD_VR_INVALID_REWARDS_AMOUNT);

    uint256 claimedAmount;
    for (uint256 i; i < _assets.length; ++i) {
      claimedAmount += _claimRewards(_assets[i], _amounts[i], msg.sender, _to);
    }

    return claimedAmount;
  }

  function getUserAssetData(address user, address asset)
    public
    view
    returns (
      uint256,
      uint256,
      uint256
    )
  {
    UserData storage userData = assets[asset].users[user];
    return (userData.index, userData.expectedRewards, userData.claimableRewards);
  }

  function getAssetData(address asset)
    public
    view
    returns (
      uint256,
      address,
      address,
      uint256
    )
  {
    return (
      assets[asset].index,
      assets[asset].yieldAddress,
      assets[asset].rewardToken,
      assets[asset].lastAvailableRewards
    );
  }

  /**
   * @dev returns the revision of the implementation contract
   */
  function getRevision() internal pure override returns (uint256) {
    return REVISION;
  }