Verified contractExactBUSL-1.1
LVLidoVaultUtil
Address0xfb717039cd23055bbe771c68ef3013731c6afe7d
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,493,381
- Creation transaction
- 0x726c2dc853…12c6431808
41 files
- src/LVLidoVaultUtil.solmain21.2 KB
- lib/chainlink/contracts/src/v0.8/automation/AutomationBase.sol692 B
- lib/chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol296 B
- lib/chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol2.33 KB
- lib/chainlink/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol2.37 KB
- lib/chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsClient.sol736 B
- lib/chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol5.3 KB
- lib/chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol6.3 KB
- lib/chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsResponse.sol3.4 KB
- lib/chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol645 B
- lib/chainlink/contracts/src/v0.8/vendor/@ensdomains/buffer/v0.1.0/Buffer.sol8.88 KB
- lib/chainlink/contracts/src/v0.8/vendor/solidity-cborutils/v2.0.0/CBOR.sol7.43 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- src/LVLidoVaultUpkeeper.sol13.79 KB
- src/interfaces/ILVLidoVault.sol5.78 KB
- src/interfaces/IPoolInfoUtils.sol14.03 KB
- src/interfaces/pool/IERC3156FlashBorrower.sol729 B
- src/interfaces/pool/IERC3156FlashLender.sol1.43 KB
- src/interfaces/pool/IPool.sol1.64 KB
- src/interfaces/pool/commons/IPoolBorrowerActions.sol613 B
- src/interfaces/pool/commons/IPoolDerivedState.sol1.68 KB
- src/interfaces/pool/commons/IPoolErrors.sol5.97 KB
- src/interfaces/pool/commons/IPoolEvents.sol13.53 KB
- src/interfaces/pool/commons/IPoolImmutables.sol917 B
- src/interfaces/pool/commons/IPoolKickerActions.sol1.66 KB
- src/interfaces/pool/commons/IPoolLPActions.sol2.72 KB
- src/interfaces/pool/commons/IPoolLenderActions.sol3.71 KB
- src/interfaces/pool/commons/IPoolSettlerActions.sol824 B
- src/interfaces/pool/commons/IPoolState.sol17.21 KB
- src/interfaces/pool/commons/IPoolTakerActions.sol2.31 KB
- src/interfaces/pool/erc20/IERC20Pool.sol1.17 KB
- src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol2.23 KB
- src/interfaces/pool/erc20/IERC20PoolEvents.sol1.21 KB
- src/interfaces/pool/erc20/IERC20PoolImmutables.sol377 B
- src/interfaces/pool/erc20/IERC20PoolLenderActions.sol790 B
- src/interfaces/vault/ILidoWithdrawal.sol1.57 KB
- src/interfaces/vault/IWeth.sol193 B
- src/interfaces/vault/IWsteth.sol1.25 KB
- src/libraries/VaultLib.sol3.67 KB
src/LVLidoVaultUtil.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {ILVLidoVault} from "./interfaces/ILVLidoVault.sol";
import {LVLidoVaultUpkeeper} from "./LVLidoVaultUpkeeper.sol";
import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol";
import {FunctionsClient} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";
import {IWsteth} from "./interfaces/vault/IWsteth.sol";
import {VaultLib} from "./libraries/VaultLib.sol";
import {IPoolInfoUtils} from "./interfaces/IPoolInfoUtils.sol";
import {IERC20Pool} from "./interfaces/pool/erc20/IERC20Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWeth} from "./interfaces/vault/IWeth.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract LVLidoVaultUtil is AutomationCompatibleInterface, Ownable, FunctionsClient {
using FunctionsRequest for FunctionsRequest.Request;
ILVLidoVault public LVLidoVault;
LVLidoVaultUpkeeper public lvLidoVaultUpkeeper;
IPoolInfoUtils public constant poolInfoUtils = IPoolInfoUtils(0x30c5eF2997d6a882DE52c4ec01B6D0a5e5B4fAAE);
uint256 stEthPerToken = IWsteth(address(VaultLib.COLLATERAL_TOKEN)).stEthPerToken();
AggregatorV3Interface internal stethUsdPriceFeed;
AggregatorV3Interface internal ethUsdPriceFeed;
uint8 public constant PRICE_FEED_DECIMALS = 8;
// Each top-up tranche is triggered after an additional ≈1.1 % market draw-down
// (1 / leverageFactor when leverageFactor≈15). Three tranches correspond to
// 1.11 %, 2.22 %, 3.33 % cumulative price moves, after which liquidation may be allowed.
uint256 public constant FACTOR_COLLATERAL_INCREASE = 11e15; // 1.1 %
// Exactly three collateral-lender tranches; when the counter reaches 3 we switch to allowKick.
uint256 public constant MAX_TRANCHES = 3;
uint256 public constant lidoClaimDelay = 7 days;
// Rate is set by the LVLidoVault contract
uint256 public upperBoundRate = 0;
uint256 public lowerBoundRate = 0;
// Receipt hash for cryptographic proof verification
// string public receiptHash;
// uint256 public rate = 221e14;
bool public updateRateNeeded = true;
uint256 public s_lastUpkeepTimeStamp;
uint256 public s_requestCounter;
uint64 public s_subscriptionId;
uint32 public s_fulfillGasLimit;
bytes32 public s_lastRequestId;
bytes public s_requestCBOR;
bytes public s_lastResponse;
bytes public s_lastError;
address public s_forwarderAddress;
constructor(address _LVLidoVault) Ownable(msg.sender) FunctionsClient(VaultLib.router) {
LVLidoVault = ILVLidoVault(_LVLidoVault);
stethUsdPriceFeed = AggregatorV3Interface(0xCfE54B5cD566aB89272946F602D76Ea879CAb4a8);
ethUsdPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// Set rate bounds: 0.5% to 10% (in 1e18 scale)
lowerBoundRate = 5e15; // 0.5%
upperBoundRate = 1e17; // 10%
}
modifier onlyForwarder() {
if (msg.sender != s_forwarderAddress && msg.sender != address(this)) {
revert VaultLib.OnlyForwarder();
}
_;
}
modifier onlyLVLidoVault() {
if (msg.sender != address(LVLidoVault)) {
revert VaultLib.Unauthorized();
}
_;
}
function getWstethToWeth(uint256 _amount) public view returns (uint256) {
// WSTETH -> STETH -> USD -> ETH -> USD -> WETH
(, int256 stethPrice,,,) = stethUsdPriceFeed.latestRoundData();
uint256 stethAmount = _amount * IWsteth(VaultLib.COLLATERAL_TOKEN).stEthPerToken() / 1e18;
// STETH -> USD
uint256 stethValueScaled = stethAmount * uint256(stethPrice);
// USD -> ETH = WETH
(, int256 ethPrice,,,) = ethUsdPriceFeed.latestRoundData();
return stethValueScaled / uint256(ethPrice);
}
function checkUpkeep(bytes calldata) public view override returns (bool upkeepNeeded, bytes memory performData) {
// Get the rate for the term if it has passed and auction hasn't happened (Ajna debt 0)
IERC20Pool pool = LVLidoVault.pool();
(uint256 debt,,,) = poolInfoUtils.borrowerInfo(address(pool), address(LVLidoVault));
if (updateRateNeeded && block.timestamp > (LVLidoVault.epochStart() + LVLidoVault.termDuration()) && debt > 0) {
upkeepNeeded = true;
performData = abi.encode(221); // Task ID 221: Get new rate
return (upkeepNeeded, performData);
}
// If no epoch has started yet or currentRedemptionRate is 0, no upkeep needed
uint256 currentRedemptionRate = LVLidoVault.currentRedemptionRate();
if (currentRedemptionRate == 0) {
return (false, performData);
}
// Calculate the market rate rather than the redemption rate
uint256 newRedemptionRate = getWstethToWeth(1e18);
int256 percentageDifferenceRedemptionRate = (
(int256(newRedemptionRate) - int256(currentRedemptionRate)) * 1e18
) / int256(currentRedemptionRate); // Drawdown percentage
int256 currentThreshold = LVLidoVault.priceDifferencethreshold()
- int256(FACTOR_COLLATERAL_INCREASE * LVLidoVault.collateralLenderTraunche()); // -1% - 33% * tranche_num
if (
LVLidoVault.epochStarted() && block.timestamp < (LVLidoVault.epochStart() + LVLidoVault.termDuration())
&& debt > 0
) {
uint256 tranchesToTrigger = 0;
int256 checkThreshold = LVLidoVault.priceDifferencethreshold(); // -1%
uint256 collateralLenderTraunche = LVLidoVault.collateralLenderTraunche();
while (
percentageDifferenceRedemptionRate < checkThreshold
&& tranchesToTrigger + collateralLenderTraunche < MAX_TRANCHES
) {
tranchesToTrigger++;
// -1% - 33% * (0 + 1) = -34%
// -1% - 33% * (0 + 2) = -67%
// -1% - 33% * (0 + 3) = -100%
checkThreshold = LVLidoVault.priceDifferencethreshold()
- int256(FACTOR_COLLATERAL_INCREASE * (collateralLenderTraunche + tranchesToTrigger));
}
uint256 totalCLDepositsUnutilized = LVLidoVault.totalCLDepositsUnutilized();
if (
tranchesToTrigger > 0 && tranchesToTrigger + collateralLenderTraunche <= MAX_TRANCHES
&& totalCLDepositsUnutilized > 0
) {
// Equal-sized tranche approach (Josh): add 1/N of remaining protector funds
uint256 remainingTranches = MAX_TRANCHES - collateralLenderTraunche;
if (remainingTranches == 0) remainingTranches = 1;
uint256 collateralToAddToPreventLiquidation =
LVLidoVault.totalCLDepositsUnutilized() / remainingTranches;
if (collateralToAddToPreventLiquidation > 0) {
upkeepNeeded = true;
performData = abi.encode(0); // Task ID 0: Add collateral (Avoid Liquidation)
return (upkeepNeeded, performData);
}
} else if (tranchesToTrigger + collateralLenderTraunche >= MAX_TRANCHES) {
upkeepNeeded = true;
performData = abi.encode(3); // Task ID 3: Allow kick
return (upkeepNeeded, performData);
}
} else if (
LVLidoVault.epochStarted() && block.timestamp > (LVLidoVault.epochStart() + LVLidoVault.termDuration())
&& LVLidoVault.getAllowKick() == false
) {
if (debt == 0) {
return (true, abi.encode(2)); // Auction happened and debt was cleared, queue task ID 2
} else if (!LVLidoVault.fundsQueued()) {
// See if Ajna debt is 0 or not
(uint256 currentDebt,,,) = poolInfoUtils.borrowerInfo(address(LVLidoVault.pool()), address(LVLidoVault));
if (currentDebt == 0) {
upkeepNeeded = true;
performData = abi.encode(2); // Task ID 2: Withdraw funds
return (upkeepNeeded, performData);
}
upkeepNeeded = true;
performData = abi.encode(1); // Task ID 1: End term and queue funds
return (upkeepNeeded, performData);
} else {
// Determine how much ETH can be claimed
uint256 firstIndex = 1;
uint256 lastIndex = VaultLib.LIDO_WITHDRAWAL.getLastCheckpointIndex();
uint256[] memory requestIds = new uint256[](1);
requestIds[0] = LVLidoVault.requestId();
uint256[] memory hints = VaultLib.LIDO_WITHDRAWAL.findCheckpointHints(requestIds, firstIndex, lastIndex);
uint256[] memory claimableEthValues = VaultLib.LIDO_WITHDRAWAL.getClaimableEther(requestIds, hints);
uint256 amount = claimableEthValues[0];
if (amount > 0) {
upkeepNeeded = true;
performData = abi.encode(2); // Task ID 2: Withdraw funds
return (upkeepNeeded, performData);
}
}
}
upkeepNeeded = false;
performData = "";
return (upkeepNeeded, performData);
}
function performUpkeep(bytes calldata performData) public override onlyForwarder {
if (performData.length == 0) revert VaultLib.InvalidInput();
uint256 taskId = abi.decode(performData, (uint256));
IERC20Pool pool = LVLidoVault.pool();
(uint256 t1Debt,,,) = poolInfoUtils.borrowerInfo(address(pool), address(LVLidoVault));
if (taskId == 221 && updateRateNeeded && t1Debt > 0) {
getRate();
emit VaultLib.TermEnded(LVLidoVault.epochStart() + LVLidoVault.termDuration());
return;
}
(uint256 t0Debt, uint256 collateral,) = pool.borrowerInfo(address(LVLidoVault));
// Add collateral to Ajna pool; Logic for Avoid Liquidations
// Only proceed if we're in an active epoch
if (
LVLidoVault.epochStarted() && block.timestamp < (LVLidoVault.epochStart() + LVLidoVault.termDuration())
&& t1Debt > 0
) {
uint256 newRedemptionRate = getWstethToWeth(1e18);
// Calculate price change as percentage
int256 percentageDifferenceRedemptionRate = (
(int256(newRedemptionRate) - int256(LVLidoVault.currentRedemptionRate())) * 1e18
) / int256(LVLidoVault.currentRedemptionRate());
// Calculate how many tranches should be triggered
uint256 tranchesToTrigger = 0;
int256 checkThreshold = LVLidoVault.priceDifferencethreshold();
// Count how many thresholds have been crossed
// -20% < -1% && 0 +
while (
percentageDifferenceRedemptionRate < checkThreshold
&& tranchesToTrigger + LVLidoVault.collateralLenderTraunche() < MAX_TRANCHES
) {
tranchesToTrigger++;
checkThreshold = LVLidoVault.priceDifferencethreshold()
- int256(FACTOR_COLLATERAL_INCREASE * (LVLidoVault.collateralLenderTraunche() + tranchesToTrigger));
}
if (
tranchesToTrigger > 0 && tranchesToTrigger + LVLidoVault.collateralLenderTraunche() <= MAX_TRANCHES
&& LVLidoVault.totalCLDepositsUnutilized() > 0
) {
// Equal-sized tranche approach (Josh): add 1/N of remaining protector funds
uint256 remainingTranches = MAX_TRANCHES - LVLidoVault.collateralLenderTraunche();
if (remainingTranches == 0) remainingTranches = 1;
uint256 collateralToAddToPreventLiquidation =
LVLidoVault.totalCLDepositsUnutilized() / remainingTranches;
if (collateralToAddToPreventLiquidation > 0) {
LVLidoVault.avoidLiquidation(collateralToAddToPreventLiquidation);
LVLidoVault.setCollateralLenderTraunche(LVLidoVault.collateralLenderTraunche() + tranchesToTrigger);
LVLidoVault.setCurrentRedemptionRate(newRedemptionRate);
}
} else if (tranchesToTrigger + LVLidoVault.collateralLenderTraunche() >= MAX_TRANCHES) {
LVLidoVault.setAllowKick(true);
}
}
// Request withdrawals
else if (
LVLidoVault.epochStarted() && block.timestamp > (LVLidoVault.epochStart() + LVLidoVault.termDuration())
&& !updateRateNeeded && LVLidoVault.getAllowKick() == false
) {
if (taskId == 1 && t1Debt > 0) {
uint256 approxPercentFinalInterest =
(LVLidoVault.rate() * ((block.timestamp - LVLidoVault.epochStart()) + lidoClaimDelay)) / 365 days;
uint256 stethPerWsteth = getWstethToWeth(1e18);
LVLidoVault.setCurrentRedemptionRate(stethPerWsteth);
emit VaultLib.RedemptionRateUpdated(stethPerWsteth);
uint256 approxCTForClaim =
(LVLidoVault.totalBorrowAmount() * (1e18 + uint256(approxPercentFinalInterest))) / stethPerWsteth;
require(
LVLidoVault.approveForProxy(
VaultLib.COLLATERAL_TOKEN, address(VaultLib.LIDO_WITHDRAWAL), approxCTForClaim
),
"Approval failure."
);
// Todo: Debt exceeds borrower leveraged collateral + epoch collateralLender funds (utilized + unutilized)
uint256[] memory amounts = new uint256[](1);
amounts[0] = approxCTForClaim;
uint256 _requestId = LVLidoVault.requestWithdrawalsWstETH(amounts);
emit VaultLib.FundsQueued(_requestId, approxCTForClaim);
}
// Withdraw funds, End epoch - delegated to LVLidoVaultUpkeeper
else if (taskId == 2) {
// Delegate epoch closing to LVLidoVaultUpkeeper to reduce contract size
lvLidoVaultUpkeeper.closeEpoch(t1Debt, collateral);
updateRateNeeded = true;
}
}
}
function performTask() external {
(bool upkeepNeeded, bytes memory performData) = this.checkUpkeep("0x");
if (upkeepNeeded) {
// Temporarily store the forwarder and set it to this contract
address originalForwarder = s_forwarderAddress;
s_forwarderAddress = address(this);
// Make external call to performUpkeep with the memory data
this.performUpkeep(performData);
// Restore original forwarder
s_forwarderAddress = originalForwarder;
}
else {
revert("No upkeep needed");
}
}
// CHAINLINK FUNCTIONS
/**
* @notice Sets the forwarder address for meta-transactions.
* @dev Can only be called by the owner.
* @param forwarderAddress The new forwarder address.
*/
function setForwarderAddress(address forwarderAddress) public {
require(msg.sender == LVLidoVault.owner(), "Only callable by LVLidoVault");
if (forwarderAddress == address(0)) revert VaultLib.InvalidInput(); // Zero address check for security
emit VaultLib.ForwarderAddressUpdated(s_forwarderAddress, forwarderAddress);
s_forwarderAddress = forwarderAddress;
}
/**
* @notice Sets the LVLidoVaultUpkeeper contract address
* @dev Can only be called by the LVLidoVault owner
* @param _upkeeper The address of the LVLidoVaultUpkeeper contract
*/
function setLVLidoVaultUpkeeper(address _upkeeper) public {
require(msg.sender == LVLidoVault.owner(), "Only callable by LVLidoVault");
if (_upkeeper == address(0)) revert VaultLib.InvalidInput();
lvLidoVaultUpkeeper = LVLidoVaultUpkeeper(_upkeeper);
}
/**
* @notice Sets the bytes representing the CBOR-encoded FunctionsRequest.Request that is sent when performUpkeep is called
*
* @param _subscriptionId The Functions billing subscription ID used to pay for Functions requests
* @param _fulfillGasLimit Maximum amount of gas used to call the client contract's `handleOracleFulfillment` function
* @param requestCBOR Bytes representing the CBOR-encoded FunctionsRequest.Request
*/
function setRequest(bytes memory requestCBOR, uint64 _subscriptionId, uint32 _fulfillGasLimit) external {
require(msg.sender == LVLidoVault.owner(), "Only callable by LVLidoVault");
s_subscriptionId = _subscriptionId;
s_fulfillGasLimit = _fulfillGasLimit;
s_requestCBOR = requestCBOR;
}
/**
* @notice Sends a request to Chainlink Functions to fetch and compute the new rate
* @dev This function attempts to send a request using the router contract and handles any errors
* that may occur during the request.
*/
function getRate() internal {
// Update state first
s_requestCounter = s_requestCounter + 1;
try i_router.sendRequest(
s_subscriptionId, s_requestCBOR, FunctionsRequest.REQUEST_DATA_VERSION, s_fulfillGasLimit, VaultLib.donId
) returns (bytes32 requestId_) {
s_lastRequestId = requestId_;
emit RequestSent(requestId_);
} catch Error(string memory reason) {
emit VaultLib.RequestRevertedWithErrorMsg(reason);
LVLidoVault.updateRate(0);
updateRateNeeded = false;
} catch (bytes memory data) {
emit VaultLib.RequestRevertedWithoutErrorMsg(data);
LVLidoVault.updateRate(0);
updateRateNeeded = false;
}
}
/**
* @notice Processes Chainlink Functions response
* @dev Decodes pre-aggregated rate sums (1e27) and calculates average APR (1e18)
* @param requestId Chainlink request ID
* @param response Encoded (sumLiquidityRates, sumBorrowRates, numRates)
* @param err Error data if any
*/
function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal override {
// Store request metadata for tracking and debugging purposes
s_lastRequestId = requestId;
s_lastResponse = response;
s_lastError = err;
s_lastUpkeepTimeStamp = block.timestamp;
// If there's an error in the response, log it and exit early
if (err.length > 0) {
emit VaultLib.OCRResponse(requestId, response, LVLidoVault.rate(), err);
LVLidoVault.updateRate(0);
updateRateNeeded = false;
return;
}
// Validate response data exists
if (response.length == 0) {
emit VaultLib.OCRResponse(requestId, response, LVLidoVault.rate(), abi.encodePacked("Empty response"));
LVLidoVault.updateRate(0);
updateRateNeeded = false;
return;
}
// Decode the aggregated rate data from Chainlink Functions
(uint256 sumLiquidityRates_1e27, uint256 sumVariableBorrowRates_1e27, uint256 numRates) =
abi.decode(response, (uint256, uint256, uint256));
// receiptHash = hash;
// Ensure we have valid rate data to process
// If numRates is 0, trigger fallback rate from Aave
if (numRates == 0) {
emit VaultLib.OCRResponse(requestId, response, LVLidoVault.rate(), abi.encodePacked("Decoded response is empty"));
LVLidoVault.updateRate(0);
updateRateNeeded = false;
return;
}
// Calculate the average APR by:
// 1. Adding supply and borrow rates
// 2. Dividing by 2 to get the average between supply and borrow
// 3. Dividing by numRates to get the average across all protocols
// 4. Converting from 1e27 to 1e18 scale by dividing by 1e9
uint256 rate = (sumLiquidityRates_1e27 + sumVariableBorrowRates_1e27) / (2 * numRates * 1e9);
// Validate rate is within bounds before updating
if (rate < lowerBoundRate || rate > upperBoundRate) {
emit VaultLib.OCRResponse(requestId, response, LVLidoVault.rate(), abi.encodePacked("Rate out of bounds"));
// Don't update the rate if it's outside bounds
LVLidoVault.updateRate(0);
updateRateNeeded = false;
return;
}
// Rate is within bounds, proceed with update
LVLidoVault.updateRate(rate);
updateRateNeeded = false; // Mark that we've successfully updated the rate
emit VaultLib.OCRResponse(requestId, response, rate, err);
}
}
lib/chainlink/contracts/src/v0.8/automation/AutomationBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AutomationBase {
error OnlySimulatedBackend();
/**
* @notice method that allows it to be simulated via eth_call by checking that
* the sender is the zero address.
*/
function _preventExecution() internal view {
// solhint-disable-next-line avoid-tx-origin
if (tx.origin != address(0) && tx.origin != address(0x1111111111111111111111111111111111111111)) {
revert OnlySimulatedBackend();
}
}
/**
* @notice modifier that allows it to be simulated via eth_call by checking
* that the sender is the zero address.
*/
modifier cannotExecute() {
_preventExecution();
_;
}
}
lib/chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {AutomationBase} from "./AutomationBase.sol";
import {AutomationCompatibleInterface} from "./interfaces/AutomationCompatibleInterface.sol";
abstract contract AutomationCompatible is AutomationBase, AutomationCompatibleInterface {}
lib/chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AutomationCompatibleInterface {
/**
* @notice method that is simulated by the keepers to see if any work actually
* needs to be performed. This method does does not actually need to be
* executable, and since it is only ever simulated it can consume lots of gas.
* @dev To ensure that it is never called, you may want to add the
* cannotExecute modifier from KeeperBase to your implementation of this
* method.
* @param checkData specified in the upkeep registration so it is always the
* same for a registered upkeep. This can easily be broken down into specific
* arguments using `abi.decode`, so multiple upkeeps can be registered on the
* same contract and easily differentiated by the contract.
* @return upkeepNeeded boolean to indicate whether the keeper should call
* performUpkeep or not.
* @return performData bytes that the keeper should call performUpkeep with, if
* upkeep is needed. If you would like to encode data to decode later, try
* `abi.encode`.
*/
function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
/**
* @notice method that is actually executed by the keepers, via the registry.
* The data returned by the checkUpkeep simulation will be passed into
* this method to actually be executed.
* @dev The input to this method should not be trusted, and the caller of the
* method should not even be restricted to any single registry. Anyone should
* be able call it, and the input should be validated, there is no guarantee
* that the data passed in is the performData returned from checkUpkeep. This
* could happen due to malicious keepers, racing keepers, or simply a state
* change while the performUpkeep transaction is waiting for confirmation.
* Always validate the data passed in.
* @param performData is the data which was passed back from the checkData
* simulation. If it is encoded, it can easily be decoded into other types by
* calling `abi.decode`. This data should not be trusted, and should be
* validated against the contract's current state.
*/
function performUpkeep(bytes calldata performData) external;
}
lib/chainlink/contracts/src/v0.8/functions/v1_0_0/FunctionsClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {IFunctionsRouter} from "./interfaces/IFunctionsRouter.sol";
import {IFunctionsClient} from "./interfaces/IFunctionsClient.sol";
import {FunctionsRequest} from "./libraries/FunctionsRequest.sol";
/// @title The Chainlink Functions client contract
/// @notice Contract developers can inherit this contract in order to make Chainlink Functions requests
abstract contract FunctionsClient is IFunctionsClient {
using FunctionsRequest for FunctionsRequest.Request;
IFunctionsRouter internal immutable i_router;
event RequestSent(bytes32 indexed id);
event RequestFulfilled(bytes32 indexed id);
error OnlyRouterCanFulfill();
constructor(address router) {
i_router = IFunctionsRouter(router);
}
/// @notice Sends a Chainlink Functions request
/// @param data The CBOR encoded bytes data for a Functions request
/// @param subscriptionId The subscription ID that will be charged to service the request
/// @param callbackGasLimit the amount of gas that will be available for the fulfillment callback
/// @return requestId The generated request ID for this request
function _sendRequest(
bytes memory data,
uint64 subscriptionId,
uint32 callbackGasLimit,
bytes32 donId
) internal returns (bytes32) {
bytes32 requestId = i_router.sendRequest(
subscriptionId,
data,
FunctionsRequest.REQUEST_DATA_VERSION,
callbackGasLimit,
donId
);
emit RequestSent(requestId);
return requestId;
}
/// @notice User defined function to handle a response from the DON
/// @param requestId The request ID, returned by sendRequest()
/// @param response Aggregated response from the execution of the user's source code
/// @param err Aggregated error from the execution of the user code or from the execution pipeline
/// @dev Either response or error parameter will be set, but never both
function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal virtual;
/// @inheritdoc IFunctionsClient
function handleOracleFulfillment(bytes32 requestId, bytes memory response, bytes memory err) external override {
if (msg.sender != address(i_router)) {
revert OnlyRouterCanFulfill();
}
fulfillRequest(requestId, response, err);
emit RequestFulfilled(requestId);
}
}
lib/chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/// @title Chainlink Functions client interface.
interface IFunctionsClient {
/// @notice Chainlink Functions response handler called by the Functions Router
/// during fullilment from the designated transmitter node in an OCR round.
/// @param requestId The requestId returned by FunctionsClient.sendRequest().
/// @param response Aggregated response from the request's source code.
/// @param err Aggregated error either from the request's source code or from the execution pipeline.
/// @dev Either response or error parameter will be set, but never both.
function handleOracleFulfillment(bytes32 requestId, bytes memory response, bytes memory err) external;
}
lib/chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {FunctionsResponse} from "../libraries/FunctionsResponse.sol";
/// @title Chainlink Functions Router interface.
interface IFunctionsRouter {
/// @notice The identifier of the route to retrieve the address of the access control contract
/// The access control contract controls which accounts can manage subscriptions
/// @return id - bytes32 id that can be passed to the "getContractById" of the Router
function getAllowListId() external view returns (bytes32);
/// @notice Set the identifier of the route to retrieve the address of the access control contract
/// The access control contract controls which accounts can manage subscriptions
function setAllowListId(bytes32 allowListId) external;
/// @notice Get the flat fee (in Juels of LINK) that will be paid to the Router owner for operation of the network
/// @return adminFee
function getAdminFee() external view returns (uint72 adminFee);
/// @notice Sends a request using the provided subscriptionId
/// @param subscriptionId - A unique subscription ID allocated by billing system,
/// a client can make requests from different contracts referencing the same subscription
/// @param data - CBOR encoded Chainlink Functions request data, use FunctionsClient API to encode a request
/// @param dataVersion - Gas limit for the fulfillment callback
/// @param callbackGasLimit - Gas limit for the fulfillment callback
/// @param donId - An identifier used to determine which route to send the request along
/// @return requestId - A unique request identifier
function sendRequest(
uint64 subscriptionId,
bytes calldata data,
uint16 dataVersion,
uint32 callbackGasLimit,
bytes32 donId
) external returns (bytes32);
/// @notice Sends a request to the proposed contracts
/// @param subscriptionId - A unique subscription ID allocated by billing system,
/// a client can make requests from different contracts referencing the same subscription
/// @param data - CBOR encoded Chainlink Functions request data, use FunctionsClient API to encode a request
/// @param dataVersion - Gas limit for the fulfillment callback
/// @param callbackGasLimit - Gas limit for the fulfillment callback
/// @param donId - An identifier used to determine which route to send the request along
/// @return requestId - A unique request identifier
function sendRequestToProposed(
uint64 subscriptionId,
bytes calldata data,
uint16 dataVersion,
uint32 callbackGasLimit,
bytes32 donId
) external returns (bytes32);
/// @notice Fulfill the request by:
/// - calling back the data that the Oracle returned to the client contract
/// - pay the DON for processing the request
/// @dev Only callable by the Coordinator contract that is saved in the commitment
/// @param response response data from DON consensus
/// @param err error from DON consensus
/// @param juelsPerGas - current rate of juels/gas
/// @param costWithoutFulfillment - The cost of processing the request (in Juels of LINK ), without fulfillment
/// @param transmitter - The Node that transmitted the OCR report
/// @param commitment - The parameters of the request that must be held consistent between request and response time
/// @return fulfillResult -
/// @return callbackGasCostJuels -
function fulfill(
bytes memory response,
bytes memory err,
uint96 juelsPerGas,
uint96 costWithoutFulfillment,
address transmitter,
FunctionsResponse.Commitment memory commitment
) external returns (FunctionsResponse.FulfillResult, uint96);
/// @notice Validate requested gas limit is below the subscription max.
/// @param subscriptionId subscription ID
/// @param callbackGasLimit desired callback gas limit
function isValidCallbackGasLimit(uint64 subscriptionId, uint32 callbackGasLimit) external view;
/// @notice Get the current contract given an ID
/// @param id A bytes32 identifier for the route
/// @return contract The current contract address
function getContractById(bytes32 id) external view returns (address);
/// @notice Get the proposed next contract given an ID
/// @param id A bytes32 identifier for the route
/// @return contract The current or proposed contract address
function getProposedContractById(bytes32 id) external view returns (address);
/// @notice Return the latest proprosal set
/// @return ids The identifiers of the contracts to update
/// @return to The addresses of the contracts that will be updated to
function getProposedContractSet() external view returns (bytes32[] memory, address[] memory);
/// @notice Proposes one or more updates to the contract routes
/// @dev Only callable by owner
function proposeContractsUpdate(bytes32[] memory proposalSetIds, address[] memory proposalSetAddresses) external;
/// @notice Updates the current contract routes to the proposed contracts
/// @dev Only callable by owner
function updateContracts() external;
/// @dev Puts the system into an emergency stopped state.
/// @dev Only callable by owner
function pause() external;
/// @dev Takes the system out of an emergency stopped state.
/// @dev Only callable by owner
function unpause() external;
}
lib/chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {CBOR} from "../../../vendor/solidity-cborutils/v2.0.0/CBOR.sol";
/// @title Library for encoding the input data of a Functions request into CBOR
library FunctionsRequest {
using CBOR for CBOR.CBORBuffer;
uint16 public constant REQUEST_DATA_VERSION = 1;
uint256 internal constant DEFAULT_BUFFER_SIZE = 256;
enum Location {
Inline, // Provided within the Request
Remote, // Hosted through remote location that can be accessed through a provided URL
DONHosted // Hosted on the DON's storage
}
enum CodeLanguage {
JavaScript
// In future version we may add other languages
}
struct Request {
Location codeLocation; // ════════════╸ The location of the source code that will be executed on each node in the DON
Location secretsLocation; // ═════════╸ The location of secrets that will be passed into the source code. *Only Remote secrets are supported
CodeLanguage language; // ════════════╸ The coding language that the source code is written in
string source; // ════════════════════╸ Raw source code for Request.codeLocation of Location.Inline, URL for Request.codeLocation of Location.Remote, or slot decimal number for Request.codeLocation of Location.DONHosted
bytes encryptedSecretsReference; // ══╸ Encrypted URLs for Request.secretsLocation of Location.Remote (use addSecretsReference()), or CBOR encoded slotid+version for Request.secretsLocation of Location.DONHosted (use addDONHostedSecrets())
string[] args; // ════════════════════╸ String arguments that will be passed into the source code
bytes[] bytesArgs; // ════════════════╸ Bytes arguments that will be passed into the source code
}
error EmptySource();
error EmptySecrets();
error EmptyArgs();
error NoInlineSecrets();
/// @notice Encodes a Request to CBOR encoded bytes
/// @param self The request to encode
/// @return CBOR encoded bytes
function encodeCBOR(Request memory self) internal pure returns (bytes memory) {
CBOR.CBORBuffer memory buffer = CBOR.create(DEFAULT_BUFFER_SIZE);
buffer.writeString("codeLocation");
buffer.writeUInt256(uint256(self.codeLocation));
buffer.writeString("language");
buffer.writeUInt256(uint256(self.language));
buffer.writeString("source");
buffer.writeString(self.source);
if (self.args.length > 0) {
buffer.writeString("args");
buffer.startArray();
for (uint256 i = 0; i < self.args.length; ++i) {
buffer.writeString(self.args[i]);
}
buffer.endSequence();
}
if (self.encryptedSecretsReference.length > 0) {
if (self.secretsLocation == Location.Inline) {
revert NoInlineSecrets();
}
buffer.writeString("secretsLocation");
buffer.writeUInt256(uint256(self.secretsLocation));
buffer.writeString("secrets");
buffer.writeBytes(self.encryptedSecretsReference);
}
if (self.bytesArgs.length > 0) {
buffer.writeString("bytesArgs");
buffer.startArray();
for (uint256 i = 0; i < self.bytesArgs.length; ++i) {
buffer.writeBytes(self.bytesArgs[i]);
}
buffer.endSequence();
}
return buffer.buf.buf;
}
/// @notice Initializes a Chainlink Functions Request
/// @dev Sets the codeLocation and code on the request
/// @param self The uninitialized request
/// @param codeLocation The user provided source code location
/// @param language The programming language of the user code
/// @param source The user provided source code or a url
function initializeRequest(
Request memory self,
Location codeLocation,
CodeLanguage language,
string memory source
) internal pure {
if (bytes(source).length == 0) revert EmptySource();
self.codeLocation = codeLocation;
self.language = language;
self.source = source;
}
/// @notice Initializes a Chainlink Functions Request
/// @dev Simplified version of initializeRequest for PoC
/// @param self The uninitialized request
/// @param javaScriptSource The user provided JS code (must not be empty)
function initializeRequestForInlineJavaScript(Request memory self, string memory javaScriptSource) internal pure {
initializeRequest(self, Location.Inline, CodeLanguage.JavaScript, javaScriptSource);
}
/// @notice Adds Remote user encrypted secrets to a Request
/// @param self The initialized request
/// @param encryptedSecretsReference Encrypted comma-separated string of URLs pointing to off-chain secrets
function addSecretsReference(Request memory self, bytes memory encryptedSecretsReference) internal pure {
if (encryptedSecretsReference.length == 0) revert EmptySecrets();
self.secretsLocation = Location.Remote;
self.encryptedSecretsReference = encryptedSecretsReference;
}
/// @notice Adds DON-hosted secrets reference to a Request
/// @param self The initialized request
/// @param slotID Slot ID of the user's secrets hosted on DON
/// @param version User data version (for the slotID)
function addDONHostedSecrets(Request memory self, uint8 slotID, uint64 version) internal pure {
CBOR.CBORBuffer memory buffer = CBOR.create(DEFAULT_BUFFER_SIZE);
buffer.writeString("slotID");
buffer.writeUInt64(slotID);
buffer.writeString("version");
buffer.writeUInt64(version);
self.secretsLocation = Location.DONHosted;
self.encryptedSecretsReference = buffer.buf.buf;
}
/// @notice Sets args for the user run function
/// @param self The initialized request
/// @param args The array of string args (must not be empty)
function setArgs(Request memory self, string[] memory args) internal pure {
if (args.length == 0) revert EmptyArgs();
self.args = args;
}
/// @notice Sets bytes args for the user run function
/// @param self The initialized request
/// @param args The array of bytes args (must not be empty)
function setBytesArgs(Request memory self, bytes[] memory args) internal pure {
if (args.length == 0) revert EmptyArgs();
self.bytesArgs = args;
}
}
lib/chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsResponse.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
/// @title Library of types that are used for fulfillment of a Functions request
library FunctionsResponse {
// Used to send request information from the Router to the Coordinator
struct RequestMeta {
bytes data; // ══════════════════╸ CBOR encoded Chainlink Functions request data, use FunctionsRequest library to encode a request
bytes32 flags; // ═══════════════╸ Per-subscription flags
address requestingContract; // ══╗ The client contract that is sending the request
uint96 availableBalance; // ═════╝ Common LINK balance of the subscription that is controlled by the Router to be used for all consumer requests.
uint72 adminFee; // ═════════════╗ Flat fee (in Juels of LINK) that will be paid to the Router Owner for operation of the network
uint64 subscriptionId; // ║ Identifier of the billing subscription that will be charged for the request
uint64 initiatedRequests; // ║ The number of requests that have been started
uint32 callbackGasLimit; // ║ The amount of gas that the callback to the consuming contract will be given
uint16 dataVersion; // ══════════╝ The version of the structure of the CBOR encoded request data
uint64 completedRequests; // ════╗ The number of requests that have successfully completed or timed out
address subscriptionOwner; // ═══╝ The owner of the billing subscription
}
enum FulfillResult {
FULFILLED, // 0
USER_CALLBACK_ERROR, // 1
INVALID_REQUEST_ID, // 2
COST_EXCEEDS_COMMITMENT, // 3
INSUFFICIENT_GAS_PROVIDED, // 4
SUBSCRIPTION_BALANCE_INVARIANT_VIOLATION, // 5
INVALID_COMMITMENT // 6
}
struct Commitment {
bytes32 requestId; // ═════════════════╸ A unique identifier for a Chainlink Functions request
address coordinator; // ═══════════════╗ The Coordinator contract that manages the DON that is servicing a request
uint96 estimatedTotalCostJuels; // ════╝ The maximum cost in Juels (1e18) of LINK that will be charged to fulfill a request
address client; // ════════════════════╗ The client contract that sent the request
uint64 subscriptionId; // ║ Identifier of the billing subscription that will be charged for the request
uint32 callbackGasLimit; // ═══════════╝ The amount of gas that the callback to the consuming contract will be given
uint72 adminFee; // ═══════════════════╗ Flat fee (in Juels of LINK) that will be paid to the Router Owner for operation of the network
uint72 donFee; // ║ Fee (in Juels of LINK) that will be split between Node Operators for servicing a request
uint40 gasOverheadBeforeCallback; // ║ Represents the average gas execution cost before the fulfillment callback.
uint40 gasOverheadAfterCallback; // ║ Represents the average gas execution cost after the fulfillment callback.
uint32 timeoutTimestamp; // ═══════════╝ The timestamp at which a request will be eligible to be timed out
}
}
lib/chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
lib/chainlink/contracts/src/v0.8/vendor/@ensdomains/buffer/v0.1.0/Buffer.sol
// SPDX-License-Identifier: BSD-2-Clause
pragma solidity ^0.8.4;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for appending to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
let fpm := add(32, add(ptr, capacity))
if lt(fpm, ptr) {
revert(0, 0)
}
mstore(0x40, fpm)
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Appends len bytes of a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
uint off = buf.buf.length;
uint newCapacity = off + len;
if (newCapacity > buf.capacity) {
resize(buf, newCapacity * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(newCapacity, buflen) {
mstore(bufptr, newCapacity)
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
unchecked {
uint mask = (256 ** (32 - len)) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return append(buf, data, data.length);
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
uint off = buf.buf.length;
uint offPlusOne = off + 1;
if (off >= buf.capacity) {
resize(buf, offPlusOne * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if gt(offPlusOne, mload(bufptr)) {
mstore(bufptr, offPlusOne)
}
}
return buf;
}
/**
* @dev Appends len bytes of bytes32 to a buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes32 data, uint len) private pure returns(buffer memory) {
uint off = buf.buf.length;
uint newCapacity = len + off;
if (newCapacity > buf.capacity) {
resize(buf, newCapacity * 2);
}
unchecked {
uint mask = (256 ** len) - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + newCapacity
let dest := add(bufptr, newCapacity)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(newCapacity, mload(bufptr)) {
mstore(bufptr, newCapacity)
}
}
}
return buf;
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return append(buf, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return append(buf, data, 32);
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
uint off = buf.buf.length;
uint newCapacity = len + off;
if (newCapacity > buf.capacity) {
resize(buf, newCapacity * 2);
}
uint mask = (256 ** len) - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + newCapacity
let dest := add(bufptr, newCapacity)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(newCapacity, mload(bufptr)) {
mstore(bufptr, newCapacity)
}
}
return buf;
}
}lib/chainlink/contracts/src/v0.8/vendor/solidity-cborutils/v2.0.0/CBOR.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../../@ensdomains/buffer/v0.1.0/Buffer.sol";
/**
* @dev A library for populating CBOR encoded payload in Solidity.
*
* https://datatracker.ietf.org/doc/html/rfc7049
*
* The library offers various write* and start* methods to encode values of different types.
* The resulted buffer can be obtained with data() method.
* Encoding of primitive types is staightforward, whereas encoding of sequences can result
* in an invalid CBOR if start/write/end flow is violated.
* For the purpose of gas saving, the library does not verify start/write/end flow internally,
* except for nested start/end pairs.
*/
library CBOR {
using Buffer for Buffer.buffer;
struct CBORBuffer {
Buffer.buffer buf;
uint256 depth;
}
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_TAG = 6;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
uint8 private constant TAG_TYPE_BIGNUM = 2;
uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3;
uint8 private constant CBOR_FALSE = 20;
uint8 private constant CBOR_TRUE = 21;
uint8 private constant CBOR_NULL = 22;
uint8 private constant CBOR_UNDEFINED = 23;
function create(uint256 capacity) internal pure returns(CBORBuffer memory cbor) {
Buffer.init(cbor.buf, capacity);
cbor.depth = 0;
return cbor;
}
function data(CBORBuffer memory buf) internal pure returns(bytes memory) {
require(buf.depth == 0, "Invalid CBOR");
return buf.buf.buf;
}
function writeUInt256(CBORBuffer memory buf, uint256 value) internal pure {
buf.buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
writeBytes(buf, abi.encode(value));
}
function writeInt256(CBORBuffer memory buf, int256 value) internal pure {
if (value < 0) {
buf.buf.appendUint8(
uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)
);
writeBytes(buf, abi.encode(uint256(-1 - value)));
} else {
writeUInt256(buf, uint256(value));
}
}
function writeUInt64(CBORBuffer memory buf, uint64 value) internal pure {
writeFixedNumeric(buf, MAJOR_TYPE_INT, value);
}
function writeInt64(CBORBuffer memory buf, int64 value) internal pure {
if(value >= 0) {
writeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value));
} else{
writeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(-1 - value));
}
}
function writeBytes(CBORBuffer memory buf, bytes memory value) internal pure {
writeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length));
buf.buf.append(value);
}
function writeString(CBORBuffer memory buf, string memory value) internal pure {
writeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length));
buf.buf.append(bytes(value));
}
function writeBool(CBORBuffer memory buf, bool value) internal pure {
writeContentFree(buf, value ? CBOR_TRUE : CBOR_FALSE);
}
function writeNull(CBORBuffer memory buf) internal pure {
writeContentFree(buf, CBOR_NULL);
}
function writeUndefined(CBORBuffer memory buf) internal pure {
writeContentFree(buf, CBOR_UNDEFINED);
}
function startArray(CBORBuffer memory buf) internal pure {
writeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
buf.depth += 1;
}
function startFixedArray(CBORBuffer memory buf, uint64 length) internal pure {
writeDefiniteLengthType(buf, MAJOR_TYPE_ARRAY, length);
}
function startMap(CBORBuffer memory buf) internal pure {
writeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
buf.depth += 1;
}
function startFixedMap(CBORBuffer memory buf, uint64 length) internal pure {
writeDefiniteLengthType(buf, MAJOR_TYPE_MAP, length);
}
function endSequence(CBORBuffer memory buf) internal pure {
writeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
buf.depth -= 1;
}
function writeKVString(CBORBuffer memory buf, string memory key, string memory value) internal pure {
writeString(buf, key);
writeString(buf, value);
}
function writeKVBytes(CBORBuffer memory buf, string memory key, bytes memory value) internal pure {
writeString(buf, key);
writeBytes(buf, value);
}
function writeKVUInt256(CBORBuffer memory buf, string memory key, uint256 value) internal pure {
writeString(buf, key);
writeUInt256(buf, value);
}
function writeKVInt256(CBORBuffer memory buf, string memory key, int256 value) internal pure {
writeString(buf, key);
writeInt256(buf, value);
}
function writeKVUInt64(CBORBuffer memory buf, string memory key, uint64 value) internal pure {
writeString(buf, key);
writeUInt64(buf, value);
}
function writeKVInt64(CBORBuffer memory buf, string memory key, int64 value) internal pure {
writeString(buf, key);
writeInt64(buf, value);
}
function writeKVBool(CBORBuffer memory buf, string memory key, bool value) internal pure {
writeString(buf, key);
writeBool(buf, value);
}
function writeKVNull(CBORBuffer memory buf, string memory key) internal pure {
writeString(buf, key);
writeNull(buf);
}
function writeKVUndefined(CBORBuffer memory buf, string memory key) internal pure {
writeString(buf, key);
writeUndefined(buf);
}
function writeKVMap(CBORBuffer memory buf, string memory key) internal pure {
writeString(buf, key);
startMap(buf);
}
function writeKVArray(CBORBuffer memory buf, string memory key) internal pure {
writeString(buf, key);
startArray(buf);
}
function writeFixedNumeric(
CBORBuffer memory buf,
uint8 major,
uint64 value
) private pure {
if (value <= 23) {
buf.buf.appendUint8(uint8((major << 5) | value));
} else if (value <= 0xFF) {
buf.buf.appendUint8(uint8((major << 5) | 24));
buf.buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.buf.appendUint8(uint8((major << 5) | 25));
buf.buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.buf.appendUint8(uint8((major << 5) | 26));
buf.buf.appendInt(value, 4);
} else {
buf.buf.appendUint8(uint8((major << 5) | 27));
buf.buf.appendInt(value, 8);
}
}
function writeIndefiniteLengthType(CBORBuffer memory buf, uint8 major)
private
pure
{
buf.buf.appendUint8(uint8((major << 5) | 31));
}
function writeDefiniteLengthType(CBORBuffer memory buf, uint8 major, uint64 length)
private
pure
{
writeFixedNumeric(buf, major, length);
}
function writeContentFree(CBORBuffer memory buf, uint8 value) private pure {
buf.buf.appendUint8(uint8((MAJOR_TYPE_CONTENT_FREE << 5) | value));
}
}lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
src/LVLidoVaultUpkeeper.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {ILVLidoVault} from "./interfaces/ILVLidoVault.sol";
import {VaultLib} from "./libraries/VaultLib.sol";
import {IPoolInfoUtils} from "./interfaces/IPoolInfoUtils.sol";
import {IERC20Pool} from "./interfaces/pool/erc20/IERC20Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title LVLidoVaultUpkeeper
* @notice Handles epoch closing logic extracted from LVLidoVaultUtil to reduce contract size
* @dev This contract is called by LVLidoVaultUtil.performUpkeep() for task 2 (close epoch)
* It processes Lido withdrawals, calculates debts, and distributes funds to participants
*/
contract LVLidoVaultUpkeeper {
ILVLidoVault public immutable LVLidoVault;
IPoolInfoUtils public constant poolInfoUtils = IPoolInfoUtils(0x30c5eF2997d6a882DE52c4ec01B6D0a5e5B4fAAE);
address public lvLidoVaultUtil;
error OnlyLVLidoVaultUtil();
error DebtGreaterThanAvailableFunds();
error UpkeepFailed();
modifier onlyUtil() {
if (msg.sender != lvLidoVaultUtil) revert OnlyLVLidoVaultUtil();
_;
}
constructor(address _LVLidoVault) {
LVLidoVault = ILVLidoVault(_LVLidoVault);
}
/**
* @notice Sets the LVLidoVaultUtil address that is authorized to call this contract
* @dev Can only be called by the LVLidoVault owner
* @param _util The address of the LVLidoVaultUtil contract
*/
function setLVLidoVaultUtil(address _util) external {
require(msg.sender == LVLidoVault.owner(), "Only owner");
require(_util != address(0), "Invalid address");
lvLidoVaultUtil = _util;
}
/**
* @notice Closes the current epoch by processing withdrawals, calculating debts, and distributing funds
* @dev This function handles the entire epoch closing process:
* 1. Claims Lido withdrawals if available
* 2. Calculates actual debt based on elapsed time and rate
* 3. Processes debt repayment
* 4. Calculates amounts owed to lenders, borrowers, and collateral lenders
* 5. Creates new orders for the next epoch
* 6. Cleans up epoch data
* @param t1Debt The current debt from pool info (t1 debt)
* @param collateral The current collateral amount from pool
*/
function closeEpoch(uint256 t1Debt, uint256 collateral) external onlyUtil {
IERC20Pool pool = LVLidoVault.pool();
// Determine actual debt based on elapsed time
uint256 timeElapsed = block.timestamp - LVLidoVault.epochStart();
uint256 actualDebt;
if (t1Debt > 0) {
actualDebt = (LVLidoVault.totalBorrowAmount() * (1e18 + ((LVLidoVault.rate() * timeElapsed) / 365 days))) / 1e18;
} else {
actualDebt = 0;
}
uint256 claimAmount = 0;
if (LVLidoVault.fundsQueued()) {
claimAmount = _processLidoWithdrawal(t1Debt);
}
// Process debt and calculate amounts owed
uint256 matchedLendersOwed = _processDebtAndCalculateOwed(
t1Debt,
actualDebt,
claimAmount,
pool
);
// Repay debt if needed
if (t1Debt > 0 || collateral > 0) {
LVLidoVault.repayDebtForProxy(t1Debt, collateral);
}
// Calculate collateral lenders owed (0.14% APY)
uint256 matchedCollateralLendersOwed = _calculateCollateralLendersOwed(timeElapsed);
// Calculate borrowers owed
uint256 matchedBorrowersOwed = _calculateBorrowersOwed(matchedCollateralLendersOwed);
emit VaultLib.AmountsOwed(matchedLendersOwed, matchedBorrowersOwed, matchedCollateralLendersOwed);
// Clear Ajna deposits and burn tokens
_clearDepositsAndBurnTokens(pool);
// Withdraw all Aave deposits (lender + CL) back to vault before processing matches.
// This ensures Aave funds are scoped to a single epoch and restores order amounts
// with principal + interest so they carry over correctly to the next epoch.
LVLidoVault.withdrawAllAaveDepositsForEpochClose();
// Process matches and create new orders
_processMatchesAndCreateOrders(matchedLendersOwed, matchedBorrowersOwed, matchedCollateralLendersOwed);
// Final cleanup
LVLidoVault.end_epoch();
LVLidoVault.setAllowKick(false);
}
/**
* @notice Processes Lido withdrawal claims
* @param t1Debt Current debt amount
* @return claimAmount Amount claimed from Lido
*/
function _processLidoWithdrawal(uint256 t1Debt) internal returns (uint256 claimAmount) {
uint256 firstIndex = 1;
uint256 lastIndex = VaultLib.LIDO_WITHDRAWAL.getLastCheckpointIndex();
uint256[] memory requestIds = new uint256[](1);
requestIds[0] = LVLidoVault.requestId();
uint256[] memory hints = VaultLib.LIDO_WITHDRAWAL.findCheckpointHints(requestIds, firstIndex, lastIndex);
uint256[] memory claimableEthValues = VaultLib.LIDO_WITHDRAWAL.getClaimableEther(requestIds, hints);
claimAmount = claimableEthValues[0];
if (claimAmount > 0) {
LVLidoVault.claimWithdrawal();
emit VaultLib.FundsClaimed(LVLidoVault.requestId(), claimAmount);
LVLidoVault.depositEthForWeth(claimAmount);
} else {
if (t1Debt != 0) {
revert VaultLib.NoETHToClaim();
}
}
}
/**
* @notice Processes debt repayment and calculates lenders owed
* @param t1Debt Current t1 debt
* @param actualDebt Calculated actual debt with interest
* @param claimAmount Amount claimed from Lido
* @param pool The Ajna pool
* @return matchedLendersOwed Amount owed to matched lenders
*/
function _processDebtAndCalculateOwed(
uint256 t1Debt,
uint256 actualDebt,
uint256 claimAmount,
IERC20Pool pool
) internal returns (uint256 matchedLendersOwed) {
if (actualDebt > claimAmount + LVLidoVault.totalManualRepay()) {
revert DebtGreaterThanAvailableFunds();
} else {
if (actualDebt < claimAmount) {
LVLidoVault.wethToWsteth(claimAmount - actualDebt);
} else {
LVLidoVault.setTotalManualRepay(LVLidoVault.totalManualRepay() - (actualDebt - claimAmount));
}
}
if (actualDebt > 0) {
bool mintSuccess = LVLidoVault.mintForProxy(address(LVLidoVault.testQuoteToken()), address(LVLidoVault), t1Debt);
bool approveSuccess = LVLidoVault.approveForProxy(address(LVLidoVault.testQuoteToken()), address(pool), t1Debt);
if (!mintSuccess || !approveSuccess) revert UpkeepFailed();
matchedLendersOwed = LVLidoVault.totalLenderQTUtilized() - LVLidoVault.totalBorrowAmount() + actualDebt;
} else {
matchedLendersOwed = IERC20(VaultLib.QUOTE_TOKEN).balanceOf(address(LVLidoVault))
- LVLidoVault.totalLenderQTUnutilized();
}
}
/**
* @notice Calculates amount owed to collateral lenders (0.14% APY)
* @param timeElapsed Time elapsed since epoch start
* @return matchedCollateralLendersOwed Amount owed to collateral lenders
*/
function _calculateCollateralLendersOwed(uint256 timeElapsed) internal view returns (uint256 matchedCollateralLendersOwed) {
matchedCollateralLendersOwed = (
(LVLidoVault.totalCLDepositsUnutilized() + LVLidoVault.totalCLDepositsUtilized())
* (1e18 + ((timeElapsed * 14e14) / 365 days))
) / 1e18;
uint256 totalEpochCollateral = IERC20(VaultLib.COLLATERAL_TOKEN).balanceOf(address(LVLidoVault))
- LVLidoVault.totalBorrowerCTUnutilized() - LVLidoVault.totalCollateralLenderCT();
if (matchedCollateralLendersOwed > totalEpochCollateral) {
matchedCollateralLendersOwed = totalEpochCollateral;
}
}
/**
* @notice Calculates amount owed to borrowers
* @param matchedCollateralLendersOwed Amount already allocated to collateral lenders
* @return matchedBorrowersOwed Remaining collateral owed to borrowers
*/
function _calculateBorrowersOwed(uint256 matchedCollateralLendersOwed) internal view returns (uint256 matchedBorrowersOwed) {
uint256 totalEpochCollateral = IERC20(VaultLib.COLLATERAL_TOKEN).balanceOf(address(LVLidoVault))
- LVLidoVault.totalBorrowerCTUnutilized() - LVLidoVault.totalCollateralLenderCT();
if (matchedCollateralLendersOwed > totalEpochCollateral) {
matchedBorrowersOwed = 0;
} else {
matchedBorrowersOwed = totalEpochCollateral - matchedCollateralLendersOwed;
}
}
/**
* @notice Clears Ajna deposits and burns tokens
* @param pool The Ajna pool
*/
function _clearDepositsAndBurnTokens(IERC20Pool pool) internal {
uint256 depositSize = pool.depositSize();
LVLidoVault.clearAjnaDeposits(depositSize);
bool burnCTSuccess = LVLidoVault.burnForProxy(
address(LVLidoVault.testCollateralToken()),
address(LVLidoVault),
LVLidoVault.testCollateralToken().balanceOf(address(LVLidoVault))
);
bool burnQTSuccess = LVLidoVault.burnForProxy(
address(LVLidoVault.testQuoteToken()),
address(LVLidoVault),
IERC20(address(LVLidoVault.testQuoteToken())).balanceOf(address(LVLidoVault))
);
if (!burnCTSuccess || !burnQTSuccess) revert UpkeepFailed();
}
/**
* @notice Processes epoch matches and creates new orders for participants
* @param matchedLendersOwed Amount owed to lenders
* @param matchedBorrowersOwed Amount owed to borrowers
* @param matchedCollateralLendersOwed Amount owed to collateral lenders
*/
function _processMatchesAndCreateOrders(
uint256 matchedLendersOwed,
uint256 matchedBorrowersOwed,
uint256 matchedCollateralLendersOwed
) internal {
uint256 totalLenderQTUnutilizedToAdjust;
uint256 newTotalBorrowerCT = LVLidoVault.totalBorrowerCT();
uint256 newTotalBorrowerCTUnutilized = LVLidoVault.totalBorrowerCTUnutilized();
uint256 currentEpoch = LVLidoVault.epoch();
// Process lender and borrower matches
VaultLib.MatchInfo[] memory matches = LVLidoVault.getEpochMatches(currentEpoch);
for (uint256 i = 0; i < matches.length; i++) {
VaultLib.MatchInfo memory match_ = matches[i];
uint256 newLenderQuoteAmount = (
(match_.quoteAmount + match_.reservedQuoteAmount) * matchedLendersOwed
) / LVLidoVault.totalLenderQTUtilized();
uint256 newBorrowerCTAmount = (match_.collateralAmount * matchedBorrowersOwed)
/ (LVLidoVault.totalBorrowerCT() - LVLidoVault.totalBorrowerCTUnutilized());
LVLidoVault.lenderOrdersPush(VaultLib.LenderOrder(match_.lender, newLenderQuoteAmount, 0));
LVLidoVault.borrowerOrdersPush(VaultLib.BorrowerOrder(match_.borrower, newBorrowerCTAmount));
totalLenderQTUnutilizedToAdjust += newLenderQuoteAmount;
newTotalBorrowerCTUnutilized += newBorrowerCTAmount;
newTotalBorrowerCT = newTotalBorrowerCT - match_.collateralAmount + newBorrowerCTAmount;
}
// Emit interest earned event
emit VaultLib.EpochInterestEarned(
currentEpoch,
(LVLidoVault.totalLenderQTUnutilized() + totalLenderQTUnutilizedToAdjust) > LVLidoVault.totalLenderQTUtilized()
? (LVLidoVault.totalLenderQTUnutilized() + totalLenderQTUnutilizedToAdjust) - LVLidoVault.totalLenderQTUtilized()
: 0,
newTotalBorrowerCT > LVLidoVault.totalBorrowerCT()
? newTotalBorrowerCT - LVLidoVault.totalBorrowerCT()
: 0,
matchedCollateralLendersOwed > (LVLidoVault.totalCLDepositsUnutilized() + LVLidoVault.totalCLDepositsUtilized())
? matchedCollateralLendersOwed - (LVLidoVault.totalCLDepositsUnutilized() + LVLidoVault.totalCLDepositsUtilized())
: 0
);
// Update lender totals
LVLidoVault.setTotalLenderQTUnutilized(LVLidoVault.totalLenderQTUnutilized() + totalLenderQTUnutilizedToAdjust);
LVLidoVault.setTotalLenderQTUtilized(0);
// Update borrower totals
LVLidoVault.setTotalBorrowerCT(newTotalBorrowerCT);
LVLidoVault.setTotalBorrowerCTUnutilized(newTotalBorrowerCTUnutilized);
// Delete epoch matches
LVLidoVault.deleteEpochMatches(currentEpoch);
// Process collateral lender orders
VaultLib.CollateralLenderOrder[] memory clOrders = LVLidoVault.getEpochCollateralLenderOrders(currentEpoch);
uint256 totalCLDeposits = LVLidoVault.totalCLDepositsUnutilized() + LVLidoVault.totalCLDepositsUtilized();
for (uint256 i = 0; i < clOrders.length; i++) {
VaultLib.CollateralLenderOrder memory clOrder = clOrders[i];
uint256 newCLCollateralAmount = (clOrder.collateralAmount * matchedCollateralLendersOwed) / totalCLDeposits;
LVLidoVault.collateralLenderOrdersPush(
VaultLib.CollateralLenderOrder(clOrder.collateralLender, newCLCollateralAmount)
);
LVLidoVault.setTotalCollateralLenderCT(LVLidoVault.totalCollateralLenderCT() + newCLCollateralAmount);
}
// Cleanup collateral lender epoch data
LVLidoVault.deleteEpochCollateralLenderOrders(currentEpoch);
LVLidoVault.setTotalCLDepositsUnutilized(0);
LVLidoVault.setTotalCLDepositsUtilized(0);
}
}
src/interfaces/ILVLidoVault.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {IERC20Pool} from "./pool/erc20/IERC20Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {VaultLib} from "../libraries/VaultLib.sol";
interface ILVLidoVault {
function pool() external view returns (IERC20Pool);
function totalBorrowAmount() external view returns (uint256);
function totalCLDepositsUnutilized() external view returns (uint256);
function totalCLDepositsUtilized() external view returns (uint256);
function epochStartRedemptionRate() external view returns (uint256);
function epochStart() external view returns (uint256);
function termDuration() external view returns (uint256);
function currentRedemptionRate() external view returns (uint256);
function priceDifferencethreshold() external view returns (int256);
function collateralLenderTraunche() external view returns (uint256);
function epochStarted() external view returns (bool);
function getInverseInitialCollateralLenderDebtRatio() external view returns (uint256);
function fundsQueued() external view returns (bool);
function requestId() external view returns (uint256);
function getRate() external;
function avoidLiquidation(uint256 collateralToAdd) external;
function setCollateralLenderTraunche(uint256 newTraunche) external;
function setCurrentRedemptionRate(uint256 newRate) external;
function setAllowKick(bool allow) external;
function rate() external view returns (uint256);
function approveForProxy(address token, address spender, uint256 amount) external returns (bool);
function requestWithdrawalsWstETH(uint256[] calldata amounts) external returns (uint256);
function claimWithdrawal() external;
function depositEthForWeth(uint256 amount) external;
function totalManualRepay() external view returns (uint256);
function wethToWsteth(uint256 amount) external returns (uint256);
function setTotalManualRepay(uint256 newTotal) external;
function testQuoteToken() external view returns (address);
function mintForProxy(address token, address to, uint256 amount) external returns (bool);
function totalLenderQTUtilized() external view returns (uint256);
function totalLenderQTUnutilized() external view returns (uint256);
function repayDebtForProxy(uint256 debtAmount, uint256 collateralAmount) external;
function totalBorrowerCTUnutilized() external view returns (uint256);
function totalCollateralLenderCT() external view returns (uint256);
function getLenderOrders() external view returns (VaultLib.LenderOrder[] memory);
function getLenderOrdersLength() external view returns (uint256);
function getBorrowerOrders() external view returns (VaultLib.BorrowerOrder[] memory);
function getBorrowerOrdersLength() external view returns (uint256);
function getCollateralLenderOrders() external view returns (VaultLib.CollateralLenderOrder[] memory);
function getCollateralLenderOrdersLength() external view returns (uint256);
function clearAjnaDeposits(uint256 depositSize) external;
function testCollateralToken() external view returns (IERC20);
function burnForProxy(address token, address from, uint256 amount) external returns (bool);
function totalBorrowerCT() external view returns (uint256);
function epoch() external view returns (uint256);
function getEpochMatches(uint256 epoch) external view returns (VaultLib.MatchInfo[] memory);
function lenderOrdersPush(VaultLib.LenderOrder memory order) external;
function borrowerOrdersPush(VaultLib.BorrowerOrder memory order) external;
function setTotalLenderQTUnutilized(uint256 amount) external;
function setTotalLenderQTUtilized(uint256 amount) external;
function setTotalBorrowerCT(uint256 amount) external;
function setTotalBorrowerCTUnutilized(uint256 amount) external;
function deleteEpochMatches(uint256 epoch) external;
function getEpochCollateralLenderOrders(uint256 epoch)
external
view
returns (VaultLib.CollateralLenderOrder[] memory);
function collateralLenderOrdersPush(VaultLib.CollateralLenderOrder memory order) external;
function setTotalCollateralLenderCT(uint256 amount) external;
function deleteEpochCollateralLenderOrders(uint256 epoch) external;
function setTotalCLDepositsUnutilized(uint256 amount) external;
function setTotalCLDepositsUtilized(uint256 amount) external;
function end_epoch() external;
function withdrawAllAaveDepositsForEpochClose() external;
function owner() external view returns (address);
function getAllowKick() external view returns (bool);
function updateRate(uint256 _rate) external;
function getEpochAaveCLDeposits(uint256 _epoch) external view returns (uint256);
function getUserAaveCLDeposit(address user, uint256 _epoch) external view returns (uint256);
function getAaveATokenAddress() external view returns (address);
function getAaveBalance() external view returns (uint256);
function getTotalAaveInterestAccrued() external view returns (uint256);
function getEpochAaveLenderDeposits(uint256 _epoch) external view returns (uint256);
function getAaveBalanceQuote() external view returns (uint256);
function emergencyAaveWithdrawDelay() external view returns (uint256);
function emergencyWithdrawLenderAaveForEpoch(uint256 targetEpoch) external returns (uint256);
function emergencyWithdrawCLAaveForEpoch(uint256 targetEpoch) external returns (uint256);
function emergencyClaimLenderAaveForEpoch(uint256 targetEpoch) external returns (uint256);
function emergencyClaimCLAaveForEpoch(uint256 targetEpoch) external returns (uint256);
}
src/interfaces/IPoolInfoUtils.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Info Utils contract
* @notice Contract for providing information for any deployed pool.
* @dev Pool info is calculated using same helper functions / logic as in `Pool` contracts.
*/
interface IPoolInfoUtils {
/**
* @notice Exposes status of a liquidation auction.
* @param ajnaPool_ Address of `Ajna` pool.
* @param borrower_ Identifies the loan being liquidated.
* @return kickTime_ Time auction was kicked, implying end time.
* @return collateral_ Remaining collateral available to be purchased. (`WAD`)
* @return debtToCover_ Borrower debt to be covered. (`WAD`)
* @return isCollateralized_ `True` if loan is collateralized.
* @return price_ Current price of the auction. (`WAD`)
* @return neutralPrice_ Price at which bond holder is neither rewarded nor penalized. (`WAD`)
* @return referencePrice_ Price used to determine auction start price. (`WAD`)
* @return debtToCollateral_ Borrower debt to collateral at time of kick. (`WAD`)
* @return bondFactor_ The factor used for calculating bond size. (`WAD`)
*/
function auctionStatus(address ajnaPool_, address borrower_)
external
view
returns (
uint256 kickTime_,
uint256 collateral_,
uint256 debtToCover_,
bool isCollateralized_,
uint256 price_,
uint256 neutralPrice_,
uint256 referencePrice_,
uint256 debtToCollateral_,
uint256 bondFactor_
);
/**
* @notice Returns details of an auction for a given borrower address.
* @dev Calls and returns all values from pool.auctionInfo().
* @param ajnaPool_ Address of `Ajna` pool.
* @param borrower_ Address of the borrower that is liquidated.
* @return kicker_ Address of the kicker that is kicking the auction.
* @return bondFactor_ The factor used for calculating bond size.
* @return bondSize_ The bond amount in quote token terms.
* @return kickTime_ Time the liquidation was initiated.
* @return referencePrice_ Price used to determine auction start price.
* @return neutralPrice_ `Neutral Price` of auction.
* @return debtToCollateral_ Borrower debt to collateral at time of kick, which is used in BPF for kicker's reward calculation.
* @return head_ Address of the head auction.
* @return next_ Address of the next auction in queue.
* @return prev_ Address of the prev auction in queue.
*/
function auctionInfo(address ajnaPool_, address borrower_)
external
view
returns (
address kicker_,
uint256 bondFactor_,
uint256 bondSize_,
uint256 kickTime_,
uint256 referencePrice_,
uint256 neutralPrice_,
uint256 debtToCollateral_,
address head_,
address next_,
address prev_
);
/**
* @notice Retrieves info of a given borrower in a given `Ajna` pool.
* @param ajnaPool_ Address of `Ajna` pool.
* @param borrower_ Borrower's address.
* @return debt_ Current debt owed by borrower (`WAD`).
* @return collateral_ Pledged collateral, including encumbered (`WAD`).
* @return t0Np_ `Neutral price` (`WAD`).
* @return thresholdPrice_ Borrower's `Threshold Price` (`WAD`).
*/
function borrowerInfo(address ajnaPool_, address borrower_)
external
view
returns (uint256 debt_, uint256 collateral_, uint256 t0Np_, uint256 thresholdPrice_);
/**
* @notice Get a bucket struct for a given index.
* @param ajnaPool_ Address of `Ajna` pool.
* @param index_ The index of the bucket to retrieve.
* @return price_ Bucket's price (`WAD`).
* @return quoteTokens_ Amount of quote token in bucket, `deposit + interest` (`WAD`).
* @return collateral_ Unencumbered collateral in bucket (`WAD`).
* @return bucketLP_ Outstanding `LP` balance in bucket (`WAD`).
* @return scale_ Lender interest multiplier (`WAD`).
* @return exchangeRate_ The exchange rate of the bucket, in `WAD` units.
*/
function bucketInfo(address ajnaPool_, uint256 index_)
external
view
returns (
uint256 price_,
uint256 quoteTokens_,
uint256 collateral_,
uint256 bucketLP_,
uint256 scale_,
uint256 exchangeRate_
);
/**
* @notice Returns info related to pool loans.
* @param ajnaPool_ Address of `Ajna` pool.
* @return poolSize_ The total amount of quote tokens in pool (`WAD`).
* @return loansCount_ The number of loans in pool.
* @return maxBorrower_ The address with the highest `TP` in pool.
* @return pendingInflator_ Pending inflator in pool.
* @return pendingInterestFactor_ Factor used to scale the inflator.
*/
function poolLoansInfo(address ajnaPool_)
external
view
returns (
uint256 poolSize_,
uint256 loansCount_,
address maxBorrower_,
uint256 pendingInflator_,
uint256 pendingInterestFactor_
);
/**
* @notice Returns info related to pool prices.
* @param ajnaPool_ Address of `Ajna` pool.
* @return hpb_ The price value of the current `Highest Price Bucket` (`HPB`), in `WAD` units.
* @return hpbIndex_ The index of the current `Highest Price Bucket` (`HPB`), in `WAD` units.
* @return htp_ The price value of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units.
* @return htpIndex_ The index of the current `Highest Threshold Price` (`HTP`) bucket, in `WAD` units.
* @return lup_ The price value of the current `Lowest Utilized Price` (LUP) bucket, in `WAD` units.
* @return lupIndex_ The index of the current `Lowest Utilized Price` (`LUP`) bucket, in `WAD` units.
*/
function poolPricesInfo(address ajnaPool_)
external
view
returns (uint256 hpb_, uint256 hpbIndex_, uint256 htp_, uint256 htpIndex_, uint256 lup_, uint256 lupIndex_);
/**
* @notice Returns the amount of quote token available for borrowing or removing from pool.
* @dev Calculated as the difference between pool balance and escrowed amounts locked in pool (auction bons + unclaimed reserves).
* @param ajnaPool_ Address of `Ajna` pool.
* @return amount_ The total quote token amount available to borrow or to be removed from pool, in `WAD` units.
*/
function availableQuoteTokenAmount(address ajnaPool_) external view returns (uint256 amount_);
/**
* @notice Returns info related to `Claimaible Reserve Auction`.
* @param ajnaPool_ Address of `Ajna` pool.
* @return reserves_ The amount of excess quote tokens.
* @return claimableReserves_ Denominated in quote token, or `0` if no reserves can be auctioned.
* @return claimableReservesRemaining_ Amount of claimable reserves which has not yet been taken.
* @return auctionPrice_ Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @return timeRemaining_ Seconds remaining before takes are no longer allowed.
*/
function poolReservesInfo(address ajnaPool_)
external
view
returns (
uint256 reserves_,
uint256 claimableReserves_,
uint256 claimableReservesRemaining_,
uint256 auctionPrice_,
uint256 timeRemaining_
);
/**
* @notice Returns info related to pool utilization.
* @param ajnaPool_ Address of `Ajna` pool.
* @return poolMinDebtAmount_ Minimum debt amount.
* @return poolCollateralization_ Current pool collateralization ratio.
* @return poolActualUtilization_ The current pool actual utilization, in `WAD` units.
* @return poolTargetUtilization_ The current pool Target utilization, in `WAD` units.
*/
function poolUtilizationInfo(address ajnaPool_)
external
view
returns (
uint256 poolMinDebtAmount_,
uint256 poolCollateralization_,
uint256 poolActualUtilization_,
uint256 poolTargetUtilization_
);
/**
* @notice Returns the proportion of interest rate which is awarded to lenders;
* the remainder accumulates in reserves.
* @param ajnaPool_ Address of `Ajna` pool.
* @return lenderInterestMargin_ Lender interest margin in pool.
*/
function lenderInterestMargin(address ajnaPool_) external view returns (uint256 lenderInterestMargin_);
/**
* @notice Returns bucket price for a given bucket index.
*/
function indexToPrice(uint256 index_) external pure returns (uint256);
/**
* @notice Returns bucket index for a given bucket price.
*/
function priceToIndex(uint256 price_) external pure returns (uint256);
/**
* @notice Returns current `LUP` for a given pool.
*/
function lup(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `LUP` index for a given pool.
*/
function lupIndex(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HPB` for a given pool.
*/
function hpb(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HPB` index for a given pool.
*/
function hpbIndex(address ajnaPool_) external view returns (uint256);
/**
* @notice Returns current `HTP` for a given pool.
*/
function htp(address ajnaPool_) external view returns (uint256 htp_);
/**
* @notice Calculates origination fee rate for a pool.
* @notice Calculated as greater of the current annualized interest rate divided by `52` (one week of interest) or `5` bps.
* @return Fee rate calculated from the pool interest rate.
*/
function borrowFeeRate(address ajnaPool_) external view returns (uint256);
/**
* @notice Calculates deposit fee rate for a pool.
* @notice Calculated as current annualized rate divided by 365 * 3 (8 hours of interest)
* @return Fee rate calculated from the pool interest rate.
*/
function depositFeeRate(address ajnaPool_) external view returns (uint256);
/**
* @notice Calculate the amount of quote tokens in bucket for a given amount of `LP`.
* @param lp_ The number of `LP` to calculate amounts for.
* @param index_ The price bucket index for which the value should be calculated.
* @return quoteAmount_ The exact amount of quote tokens that can be exchanged for the given `LP`, `WAD` units.
*/
function lpToQuoteTokens(address ajnaPool_, uint256 lp_, uint256 index_)
external
view
returns (uint256 quoteAmount_);
/**
* @notice Calculate the amount of collateral tokens in bucket for a given amount of `LP`.
* @param lp_ The number of `LP` to calculate amounts for.
* @param index_ The price bucket index for which the value should be calculated.
* @return collateralAmount_ The exact amount of collateral tokens that can be exchanged for the given `LP`, `WAD` units.
*/
function lpToCollateral(address ajnaPool_, uint256 lp_, uint256 index_)
external
view
returns (uint256 collateralAmount_);
}
// /**********************/
// /*** Pool Utilities ***/
// /**********************/
// /**
// * @notice Calculates encumberance for a debt amount at a given price.
// * @param debt_ The debt amount to calculate encumberance for.
// * @param price_ The price to calculate encumberance at.
// * @return encumberance_ Encumberance value.
// */
// function _encumberance(
// uint256 debt_,
// uint256 price_
// ) pure returns (uint256 encumberance_) {
// return price_ != 0 ? Maths.wdiv(Maths.wmul(COLLATERALIZATION_FACTOR , debt_), price_) : 0;
// }
// /**
// * @notice Calculates collateralization for a given debt and collateral amounts, at a given price.
// * @param debt_ The debt amount.
// * @param collateral_ The collateral amount.
// * @param price_ The price to calculate collateralization at.
// * @return Collateralization value. `1 WAD` if debt amount is `0`.
// */
// function _collateralization(
// uint256 debt_,
// uint256 collateral_,
// uint256 price_
// ) pure returns (uint256) {
// // cannot be undercollateralized if there is no debt
// if (debt_ == 0) return 1e18;
// // borrower is undercollateralized when lup at MIN_PRICE
// if (price_ == MIN_PRICE) return 0;
// return Maths.wdiv(Maths.wmul(collateral_, price_), Maths.wmul(COLLATERALIZATION_FACTOR, debt_));
// }
// /**
// * @notice Calculates target utilization for given `EMA` values.
// * @param debtColEma_ The `EMA` of debt squared to collateral.
// * @param lupt0DebtEma_ The `EMA` of `LUP * t0 debt`.
// * @return Target utilization of the pool.
// */
// function _targetUtilization(
// uint256 debtColEma_,
// uint256 lupt0DebtEma_
// ) pure returns (uint256) {
// return (lupt0DebtEma_ != 0) ? Maths.wdiv(debtColEma_, lupt0DebtEma_) : Maths.WAD;
// }
src/interfaces/pool/IERC3156FlashBorrower.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent (token precision).
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The `keccak256` hash of `ERC3156FlashBorrower.onFlashLoan`
*/
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data)
external
returns (bytes32);
}
src/interfaces/pool/IERC3156FlashLender.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {IERC3156FlashBorrower} from "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token_ The loan currency.
* @return The amount of `token` that can be borrowed (token precision).
*/
function maxFlashLoan(address token_) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token_ The loan currency.
* @param amount_ The amount of tokens lent (token precision).
* @return The amount of `token` to be charged for the loan (token precision), on top of the returned principal .
*/
function flashFee(address token_, uint256 amount_) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver_ The receiver of the tokens in the loan, and the receiver of the callback.
* @param token_ The loan currency.
* @param amount_ The amount of tokens lent (token precision).
* @param data_ Arbitrary data structure, intended to contain user-defined parameters.
* @return `True` when successful flashloan, `false` otherwise.
*/
function flashLoan(IERC3156FlashBorrower receiver_, address token_, uint256 amount_, bytes calldata data_)
external
returns (bool);
}
src/interfaces/pool/IPool.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {IPoolBorrowerActions} from "./commons/IPoolBorrowerActions.sol";
import {IPoolLPActions} from "./commons/IPoolLPActions.sol";
import {IPoolLenderActions} from "./commons/IPoolLenderActions.sol";
import {IPoolKickerActions} from "./commons/IPoolKickerActions.sol";
import {IPoolTakerActions} from "./commons/IPoolTakerActions.sol";
import {IPoolSettlerActions} from "./commons/IPoolSettlerActions.sol";
import {IPoolImmutables} from "./commons/IPoolImmutables.sol";
import {IPoolState} from "./commons/IPoolState.sol";
import {IPoolDerivedState} from "./commons/IPoolDerivedState.sol";
import {IPoolEvents} from "./commons/IPoolEvents.sol";
import {IPoolErrors} from "./commons/IPoolErrors.sol";
import {IERC3156FlashLender} from "./IERC3156FlashLender.sol";
/**
* @title Base Pool Interface
*/
interface IPool is
IPoolBorrowerActions,
IPoolLPActions,
IPoolLenderActions,
IPoolKickerActions,
IPoolTakerActions,
IPoolSettlerActions,
IPoolImmutables,
IPoolState,
IPoolDerivedState,
IPoolEvents,
IPoolErrors,
IERC3156FlashLender
{}
/// @dev Pool type enum - `ERC20` and `ERC721`
enum PoolType {
ERC20,
ERC721
}
/// @dev `ERC20` token interface.
interface IERC20Token {
function balanceOf(address account) external view returns (uint256);
function burn(uint256 amount) external;
function decimals() external view returns (uint8);
}
/// @dev `ERC721` token interface.
interface IERC721Token {
function transferFrom(address from, address to, uint256 tokenId) external;
}
src/interfaces/pool/commons/IPoolBorrowerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Borrower Actions
*/
interface IPoolBorrowerActions {
/**
* @notice Called by fully collateralized borrowers to restamp the `Np to Tp ratio` of the loan (only if loan is fully collateralized and not in auction).
* The reason for stamping the `Np to Tp ratio` on the loan is to provide some certainty to the borrower as to at what price they can expect to be liquidated.
* This action can restamp only the loan of `msg.sender`.
*/
function stampLoan() external;
}
src/interfaces/pool/commons/IPoolDerivedState.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Derived State
*/
interface IPoolDerivedState {
/**
* @notice Returns the exchange rate for a given bucket index.
* @param index_ The bucket index.
* @return exchangeRate_ Exchange rate of the bucket (`WAD` precision).
*/
function bucketExchangeRate(uint256 index_) external view returns (uint256 exchangeRate_);
/**
* @notice Returns the prefix sum of a given bucket.
* @param index_ The bucket index.
* @return The deposit up to given index (`WAD` precision).
*/
function depositUpToIndex(uint256 index_) external view returns (uint256);
/**
* @notice Returns the bucket index for a given debt amount.
* @param debt_ The debt amount to calculate bucket index for (`WAD` precision).
* @return Bucket index.
*/
function depositIndex(uint256 debt_) external view returns (uint256);
/**
* @notice Returns the total amount of quote tokens deposited in pool.
* @return Total amount of deposited quote tokens (`WAD` precision).
*/
function depositSize() external view returns (uint256);
/**
* @notice Returns the meaningful actual utilization of the pool.
* @return Deposit utilization (`WAD` precision).
*/
function depositUtilization() external view returns (uint256);
/**
* @notice Returns the scaling value of deposit at given index.
* @param index_ Deposit index.
* @return Deposit scaling (`WAD` precision).
*/
function depositScale(uint256 index_) external view returns (uint256);
}
src/interfaces/pool/commons/IPoolErrors.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Errors.
*/
interface IPoolErrors {
/**
*
*/
/**
* Common Pool Errors **
*/
/**
*
*/
/**
* @notice Adding liquidity above current auction price.
*/
error AddAboveAuctionPrice();
/**
* @notice The action cannot be executed on an active auction.
*/
error AuctionActive();
/**
* @notice Attempted auction to clear doesn't meet conditions.
*/
error AuctionNotClearable();
/**
* @notice Auction does not meet requirements to take liquidity.
*/
error AuctionNotTakeable();
/**
* @notice Head auction should be cleared prior of executing this action.
*/
error AuctionNotCleared();
/**
* @notice The auction price is greater than the arbed bucket price.
*/
error AuctionPriceGtBucketPrice();
/**
* @notice Pool already initialized.
*/
error AlreadyInitialized();
/**
* @notice Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount.
*/
error AmountLTMinDebt();
/**
* @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function.
*/
error BorrowerNotSender();
/**
* @notice Borrower has a healthy over-collateralized position.
*/
error BorrowerOk();
/**
* @notice Borrower is attempting to borrow more quote token than they have collateral for.
*/
error BorrowerUnderCollateralized();
/**
* @notice Operation cannot be executed in the same block when bucket becomes insolvent.
*/
error BucketBankruptcyBlock();
/**
* @notice User attempted to merge collateral from a lower price bucket into a higher price bucket.
*/
error CannotMergeToHigherPrice();
/**
* @notice User attempted an operation which does not exceed the dust amount, or leaves behind less than the dust amount.
*/
error DustAmountNotExceeded();
/**
* @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec).
*/
error FlashloanCallbackFailed();
/**
* @notice Balance of pool contract before flashloan is different than the balance after flashloan.
*/
error FlashloanIncorrectBalance();
/**
* @notice Pool cannot facilitate a flashloan for the specified token address.
*/
error FlashloanUnavailableForToken();
/**
* @notice User is attempting to move or pull more collateral than is available.
*/
error InsufficientCollateral();
/**
* @notice Lender is attempting to move or remove more collateral they have claim to in the bucket.
* @notice Lender is attempting to remove more collateral they have claim to in the bucket.
* @notice Lender must have enough `LP` to claim the desired amount of quote from the bucket.
*/
error InsufficientLP();
/**
* @notice Bucket must have more quote available in the bucket than the lender is attempting to claim.
*/
error InsufficientLiquidity();
/**
* @notice When increasing / decreasing `LP` allowances indexes and amounts arrays parameters should have same length.
*/
error InvalidAllowancesInput();
/**
* @notice When transferring `LP` between indices, the new index must be a valid index.
*/
error InvalidIndex();
/**
* @notice The amount used for performed action should be greater than `0`.
*/
error InvalidAmount();
/**
* @notice Borrower is attempting to borrow more quote token than is available before the supplied `limitIndex`.
*/
error LimitIndexExceeded();
/**
* @notice When moving quote token `HTP` must stay below `LUP`.
* @notice When removing quote token `HTP` must stay below `LUP`.
*/
error LUPBelowHTP();
/**
* @notice From index and to index arguments to move are the same.
*/
error MoveToSameIndex();
/**
* @notice Owner of the `LP` must have approved the new owner prior to transfer.
*/
error NoAllowance();
/**
* @notice Actor is attempting to take or clear an inactive auction.
*/
error NoAuction();
/**
* @notice No pool reserves are claimable.
*/
error NoReserves();
/**
* @notice Actor is attempting to take or clear an inactive reserves auction.
*/
error NoReservesAuction();
/**
* @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool.
*/
error NoClaim();
/**
* @notice Borrower has no debt to liquidate.
* @notice Borrower is attempting to repay when they have no outstanding debt.
*/
error NoDebt();
/**
* @notice Actor is attempting to kick with bucket price below the `LUP`.
*/
error PriceBelowLUP();
/**
* @notice Lender is attempting to remove quote tokens from a bucket that exists above active auction debt from top-of-book downward.
*/
error RemoveDepositLockedByAuctionDebt();
/**
* @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed.
*/
error ReserveAuctionTooSoon();
/**
* @notice Current block timestamp has reached or exceeded a user-provided expiration.
*/
error TransactionExpired();
/**
* @notice The address that transfer `LP` is not approved by the `LP` receiving address.
*/
error TransferorNotApproved();
/**
* @notice Owner of the `LP` attemps to transfer `LP` to same address.
*/
error TransferToSameOwner();
/**
* @notice The DebtToCollateral of the loan to be inserted in loans heap is zero.
*/
error ZeroDebtToCollateral();
}
src/interfaces/pool/commons/IPoolEvents.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Events
*/
interface IPoolEvents {
/**
*
*/
/**
* Lender events **
*/
/**
*
*/
/**
* @notice Emitted when lender adds quote token to the pool.
* @param lender Recipient that added quote tokens.
* @param index Index at which quote tokens were added.
* @param amount Amount of quote tokens added to the pool (`WAD` precision).
* @param lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).
* @param lup `LUP` calculated after deposit.
*/
event AddQuoteToken(address indexed lender, uint256 indexed index, uint256 amount, uint256 lpAwarded, uint256 lup);
/**
* @notice Emitted when lender moves quote token from a bucket price to another.
* @param lender Recipient that moved quote tokens.
* @param from Price bucket from which quote tokens were moved.
* @param to Price bucket where quote tokens were moved.
* @param amount Amount of quote tokens moved (`WAD` precision).
* @param lpRedeemedFrom Amount of `LP` removed from the `from` bucket (`WAD` precision).
* @param lpAwardedTo Amount of `LP` credited to the `to` bucket (`WAD` precision).
* @param lup `LUP` calculated after removal.
*/
event MoveQuoteToken(
address indexed lender,
uint256 indexed from,
uint256 indexed to,
uint256 amount,
uint256 lpRedeemedFrom,
uint256 lpAwardedTo,
uint256 lup
);
/**
* @notice Emitted when lender removes quote token from the pool.
* @param lender Recipient that removed quote tokens.
* @param index Index at which quote tokens were removed.
* @param amount Amount of quote tokens removed from the pool (`WAD` precision).
* @param lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).
* @param lup `LUP` calculated after removal.
*/
event RemoveQuoteToken(
address indexed lender, uint256 indexed index, uint256 amount, uint256 lpRedeemed, uint256 lup
);
/**
* @notice Emitted when lender claims collateral from a bucket.
* @param claimer Recipient that claimed collateral.
* @param index Index at which collateral was claimed.
* @param amount The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.
* @param lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).
*/
event RemoveCollateral(address indexed claimer, uint256 indexed index, uint256 amount, uint256 lpRedeemed);
/**
*
*/
/**
* Borrower events **
*/
/**
*
*/
/**
* @notice Emitted when borrower repays quote tokens to the pool and/or pulls collateral from the pool.
* @param borrower `msg.sender` or on behalf of sender.
* @param quoteRepaid Amount of quote tokens repaid to the pool (`WAD` precision).
* @param collateralPulled The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.
* @param lup `LUP` after repay.
*/
event RepayDebt(address indexed borrower, uint256 quoteRepaid, uint256 collateralPulled, uint256 lup);
/**
*
*/
/**
* Auction events **
*/
/**
*
*/
/**
* @notice Emitted when a liquidation is initiated.
* @param borrower Identifies the loan being liquidated.
* @param debt Debt the liquidation will attempt to cover (`WAD` precision).
* @param collateral Amount of collateral up for liquidation (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools).
* @param bond Bond amount locked by kicker (`WAD` precision).
*/
event Kick(address indexed borrower, uint256 debt, uint256 collateral, uint256 bond);
/**
* @notice Emitted when kickers are withdrawing funds posted as auction bonds.
* @param kicker The kicker withdrawing bonds.
* @param reciever The address receiving withdrawn bond amount.
* @param amount The bond amount that was withdrawn (`WAD` precision).
*/
event BondWithdrawn(address indexed kicker, address indexed reciever, uint256 amount);
/**
* @notice Emitted when an actor uses quote token to arb higher-priced deposit off the book.
* @param borrower Identifies the loan being liquidated.
* @param index The index of the `Highest Price Bucket` used for this take.
* @param amount Amount of quote token used to purchase collateral (`WAD` precision).
* @param collateral Amount of collateral purchased with quote token (`WAD` precision).
* @param bondChange Impact of this take to the liquidation bond (`WAD` precision).
* @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.
* @dev amount / collateral implies the auction price.
*/
event BucketTake(
address indexed borrower, uint256 index, uint256 amount, uint256 collateral, uint256 bondChange, bool isReward
);
/**
* @notice Emitted when `LP` are awarded to a taker or kicker in a bucket take.
* @param taker Actor who invoked the bucket take.
* @param kicker Actor who started the auction.
* @param lpAwardedTaker Amount of `LP` awarded to the taker (`WAD` precision).
* @param lpAwardedKicker Amount of `LP` awarded to the actor who started the auction (`WAD` precision).
*/
event BucketTakeLPAwarded(
address indexed taker, address indexed kicker, uint256 lpAwardedTaker, uint256 lpAwardedKicker
);
/**
* @notice Emitted when an actor uses quote token outside of the book to purchase collateral under liquidation.
* @param borrower Identifies the loan being liquidated.
* @param amount Amount of quote token used to purchase collateral (`WAD` precision).
* @param collateral Amount of collateral purchased with quote token (for `ERC20` pool, `WAD` precision) or number of `NFT`s purchased (for `ERC721` pool).
* @param bondChange Impact of this take to the liquidation bond (`WAD` precision).
* @param isReward `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.
* @dev amount / collateral implies the auction price.
*/
event Take(address indexed borrower, uint256 amount, uint256 collateral, uint256 bondChange, bool isReward);
/**
* @notice Emitted when an actor settles debt in a completed liquidation
* @param borrower Identifies the loan under liquidation.
* @param settledDebt Amount of pool debt settled in this transaction (`WAD` precision).
* @dev When `amountRemaining_ == 0`, the auction has been completed cleared and removed from the queue.
*/
event Settle(address indexed borrower, uint256 settledDebt);
/**
* @notice Emitted when auction is completed.
* @param borrower Address of borrower that exits auction.
* @param collateral Borrower's remaining collateral when auction completed (`WAD` precision).
*/
event AuctionSettle(address indexed borrower, uint256 collateral);
/**
* @notice Emitted when `NFT` auction is completed.
* @param borrower Address of borrower that exits auction.
* @param collateral Borrower's remaining collateral when auction completed.
* @param lp Amount of `LP` given to the borrower to compensate fractional collateral (if any, `WAD` precision).
* @param index Index of the bucket with `LP` to compensate fractional collateral.
*/
event AuctionNFTSettle(address indexed borrower, uint256 collateral, uint256 lp, uint256 index);
/**
* @notice Emitted when a `Claimaible Reserve Auction` is started.
* @param claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).
* @param auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @param currentBurnEpoch Current burn epoch.
*/
event KickReserveAuction(uint256 claimableReservesRemaining, uint256 auctionPrice, uint256 currentBurnEpoch);
/**
* @notice Emitted when a `Claimaible Reserve Auction` is taken.
* @param claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).
* @param auctionPrice Current price at which `1` quote token may be purchased, denominated in `Ajna`.
* @param currentBurnEpoch Current burn epoch.
*/
event ReserveAuction(uint256 claimableReservesRemaining, uint256 auctionPrice, uint256 currentBurnEpoch);
/**
*
*/
/**
* LP transfer events **
*/
/**
*
*/
/**
* @notice Emitted when owner increase the `LP` allowance of a spender at specified indexes with specified amounts.
* @param owner `LP` owner.
* @param spender Address approved to transfer `LP`.
* @param indexes Bucket indexes of `LP` approved.
* @param amounts `LP` amounts added (ordered by indexes, `WAD` precision).
*/
event IncreaseLPAllowance(address indexed owner, address indexed spender, uint256[] indexes, uint256[] amounts);
/**
* @notice Emitted when owner decrease the `LP` allowance of a spender at specified indexes with specified amounts.
* @param owner `LP` owner.
* @param spender Address approved to transfer `LP`.
* @param indexes Bucket indexes of `LP` approved.
* @param amounts `LP` amounts removed (ordered by indexes, `WAD` precision).
*/
event DecreaseLPAllowance(address indexed owner, address indexed spender, uint256[] indexes, uint256[] amounts);
/**
* @notice Emitted when lender removes the allowance of a spender for their `LP`.
* @param owner `LP` owner.
* @param spender Address that is having it's allowance revoked.
* @param indexes List of bucket index to remove the allowance from.
*/
event RevokeLPAllowance(address indexed owner, address indexed spender, uint256[] indexes);
/**
* @notice Emitted when lender whitelists addresses to accept `LP` from.
* @param lender Recipient that approves new owner for `LP`.
* @param transferors List of addresses that can transfer `LP` to lender.
*/
event ApproveLPTransferors(address indexed lender, address[] transferors);
/**
* @notice Emitted when lender removes addresses from the `LP` transferors whitelist.
* @param lender Recipient that approves new owner for `LP`.
* @param transferors List of addresses that won't be able to transfer `LP` to lender anymore.
*/
event RevokeLPTransferors(address indexed lender, address[] transferors);
/**
* @notice Emitted when a lender transfers their `LP` to a different address.
* @dev Used by `PositionManager.memorializePositions()`.
* @param owner The original owner address of the position.
* @param newOwner The new owner address of the position.
* @param indexes Array of price bucket indexes at which `LP` were transferred.
* @param lp Amount of `LP` transferred (`WAD` precision).
*/
event TransferLP(address owner, address newOwner, uint256[] indexes, uint256 lp);
/**
*
*/
/**
* Pool common events **
*/
/**
*
*/
/**
* @notice Emitted when `LP` are forfeited as a result of the bucket losing all assets.
* @param index The index of the bucket.
* @param lpForfeited Amount of `LP` forfeited by lenders (`WAD` precision).
*/
event BucketBankruptcy(uint256 indexed index, uint256 lpForfeited);
/**
* @notice Emitted when a flashloan is taken from pool.
* @param receiver The address receiving the flashloan.
* @param token The address of token flashloaned from pool.
* @param amount The amount of tokens flashloaned from pool (token precision).
*/
event Flashloan(address indexed receiver, address indexed token, uint256 amount);
/**
* @notice Emitted when a loan `Np to Tp ratio` is restamped.
* @param borrower Identifies the loan to update the `Np to Tp ratio`.
*/
event LoanStamped(address indexed borrower);
/**
* @notice Emitted when pool interest rate is reset. This happens when `interest rate > 10%` and `debtEma < 5%` of `depositEma`
* @param oldRate Old pool interest rate.
* @param newRate New pool interest rate.
*/
event ResetInterestRate(uint256 oldRate, uint256 newRate);
/**
* @notice Emitted when pool interest rate is updated.
* @param oldRate Old pool interest rate.
* @param newRate New pool interest rate.
*/
event UpdateInterestRate(uint256 oldRate, uint256 newRate);
/**
* @notice Emitted when interest accural or update interest overflows.
*/
event InterestUpdateFailure();
}
src/interfaces/pool/commons/IPoolImmutables.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Immutables
*/
interface IPoolImmutables {
/**
* @notice Returns the type of the pool (`0` for `ERC20`, `1` for `ERC721`).
*/
function poolType() external pure returns (uint8);
/**
* @notice Returns the address of the pool's collateral token.
*/
function collateralAddress() external pure returns (address);
/**
* @notice Returns the address of the pool's quote token.
*/
function quoteTokenAddress() external pure returns (address);
/**
* @notice Returns the `quoteTokenScale` state variable.
* @notice Token scale is also the minimum amount a lender may have in a bucket (dust amount).
* @return The precision of the quote `ERC20` token based on decimals.
*/
function quoteTokenScale() external pure returns (uint256);
}
src/interfaces/pool/commons/IPoolKickerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Kicker Actions
*/
interface IPoolKickerActions {
/**
*
*/
/**
* Liquidations **
*/
/**
*
*/
/**
* @notice Called by actors to initiate a liquidation.
* @param borrower_ Identifies the loan to liquidate.
* @param npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction.
*/
function kick(address borrower_, uint256 npLimitIndex_) external;
/**
* @notice Called by lenders to liquidate the top loan.
* @param index_ The deposit index to use for kicking the top loan.
* @param npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction.
*/
function lenderKick(uint256 index_, uint256 npLimitIndex_) external;
/**
* @notice Called by kickers to withdraw their auction bonds (the amount of quote tokens that are not locked in active auctions).
* @param recipient_ Address to receive claimed bonds amount.
* @param maxAmount_ The max amount to withdraw from auction bonds (`WAD` precision). Constrained by claimable amounts and liquidity.
* @return withdrawnAmount_ The amount withdrawn (`WAD` precision).
*/
function withdrawBonds(address recipient_, uint256 maxAmount_) external returns (uint256 withdrawnAmount_);
/**
*
*/
/**
* Reserve Auction **
*/
/**
*
*/
/**
* @notice Called by actor to start a `Claimable Reserve Auction` (`CRA`).
*/
function kickReserveAuction() external;
}
src/interfaces/pool/commons/IPoolLPActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool `LP` Actions
*/
interface IPoolLPActions {
/**
* @notice Called by `LP` owners to approve transfer of an amount of `LP` to a new owner.
* @dev Intended for use by the `PositionManager` contract.
* @param spender_ The new owner of the `LP`.
* @param indexes_ Bucket indexes from where `LP` are transferred.
* @param amounts_ The amounts of `LP` approved to transfer (`WAD` precision).
*/
function increaseLPAllowance(address spender_, uint256[] calldata indexes_, uint256[] calldata amounts_) external;
/**
* @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner.
* @dev Intended for use by the `PositionManager` contract.
* @param spender_ The new owner of the `LP`.
* @param indexes_ Bucket indexes from where `LP` are transferred.
* @param amounts_ The amounts of `LP` disapproved to transfer (`WAD` precision).
*/
function decreaseLPAllowance(address spender_, uint256[] calldata indexes_, uint256[] calldata amounts_) external;
/**
* @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner.
* @param spender_ Address that is having it's allowance revoked.
* @param indexes_ List of bucket index to remove the allowance from.
*/
function revokeLPAllowance(address spender_, uint256[] calldata indexes_) external;
/**
* @notice Called by `LP` owners to allow addresses that can transfer LP.
* @dev Intended for use by the `PositionManager` contract.
* @param transferors_ Addresses that are allowed to transfer `LP` to new owner.
*/
function approveLPTransferors(address[] calldata transferors_) external;
/**
* @notice Called by `LP` owners to revoke addresses that can transfer `LP`.
* @dev Intended for use by the `PositionManager` contract.
* @param transferors_ Addresses that are revoked to transfer `LP` to new owner.
*/
function revokeLPTransferors(address[] calldata transferors_) external;
/**
* @notice Called by `LP` owners to transfers their `LP` to a different address. `approveLpOwnership` needs to be run first.
* @dev Used by `PositionManager.memorializePositions()`.
* @param owner_ The original owner address of the position.
* @param newOwner_ The new owner address of the position.
* @param indexes_ Array of price buckets index at which `LP` were moved.
*/
function transferLP(address owner_, address newOwner_, uint256[] calldata indexes_) external;
}
src/interfaces/pool/commons/IPoolLenderActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Lender Actions
*/
interface IPoolLenderActions {
/**
*
*/
/**
* Quote/collateral management functions **
*/
/**
*
*/
/**
* @notice Called by lenders to add an amount of credit at a specified price bucket.
* @param amount_ The amount of quote token to be added by a lender (`WAD` precision).
* @param index_ The index of the bucket to which the quote tokens will be added.
* @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.
* @return bucketLP_ The amount of `LP` changed for the added quote tokens (`WAD` precision).
* @return addedAmount_ The amount of quote token added (`WAD` precision).
*/
function addQuoteToken(uint256 amount_, uint256 index_, uint256 expiry_)
external
returns (uint256 bucketLP_, uint256 addedAmount_);
/**
* @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket.
* @param maxAmount_ The maximum amount of quote token to be moved by a lender (`WAD` precision).
* @param fromIndex_ The bucket index from which the quote tokens will be removed.
* @param toIndex_ The bucket index to which the quote tokens will be added.
* @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.
* @return fromBucketLP_ The amount of `LP` moved out from bucket (`WAD` precision).
* @return toBucketLP_ The amount of `LP` moved to destination bucket (`WAD` precision).
* @return movedAmount_ The amount of quote token moved (`WAD` precision).
*/
function moveQuoteToken(uint256 maxAmount_, uint256 fromIndex_, uint256 toIndex_, uint256 expiry_)
external
returns (uint256 fromBucketLP_, uint256 toBucketLP_, uint256 movedAmount_);
/**
* @notice Called by lenders to claim collateral from a price bucket.
* @param maxAmount_ The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) to claim.
* @param index_ The bucket index from which collateral will be removed.
* @return removedAmount_ The amount of collateral removed (`WAD` precision).
* @return redeemedLP_ The amount of `LP` used for removing collateral amount (`WAD` precision).
*/
function removeCollateral(uint256 maxAmount_, uint256 index_)
external
returns (uint256 removedAmount_, uint256 redeemedLP_);
/**
* @notice Called by lenders to remove an amount of credit at a specified price bucket.
* @param maxAmount_ The max amount of quote token to be removed by a lender (`WAD` precision).
* @param index_ The bucket index from which quote tokens will be removed.
* @return removedAmount_ The amount of quote token removed (`WAD` precision).
* @return redeemedLP_ The amount of `LP` used for removing quote tokens amount (`WAD` precision).
*/
function removeQuoteToken(uint256 maxAmount_, uint256 index_)
external
returns (uint256 removedAmount_, uint256 redeemedLP_);
/**
*
*/
/**
* Interest update function **
*/
/**
*
*/
/**
* @notice Called by actors to update pool interest rate (can be updated only once in a `12` hours period of time).
*/
function updateInterest() external;
}
src/interfaces/pool/commons/IPoolSettlerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Settler Actions
*/
interface IPoolSettlerActions {
/**
* @notice Called by actors to settle an amount of debt in a completed liquidation.
* @param borrowerAddress_ Address of the auctioned borrower.
* @param maxDepth_ Measured from `HPB`, maximum number of buckets deep to settle debt.
* @return collateralSettled_ Amount of collateral settled.
* @return isBorrowerSettled_ True if all borrower's debt is settled.
* @dev `maxDepth_` is used to prevent unbounded iteration clearing large liquidations.
*/
function settle(address borrowerAddress_, uint256 maxDepth_)
external
returns (uint256 collateralSettled_, bool isBorrowerSettled_);
}
src/interfaces/pool/commons/IPoolState.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool State
*/
interface IPoolState {
/**
* @notice Returns details of an auction for a given borrower address.
* @param borrower_ Address of the borrower that is liquidated.
* @return kicker_ Address of the kicker that is kicking the auction.
* @return bondFactor_ The factor used for calculating bond size.
* @return bondSize_ The bond amount in quote token terms.
* @return kickTime_ Time the liquidation was initiated.
* @return referencePrice_ Price used to determine auction start price.
* @return neutralPrice_ `Neutral Price` of auction.
* @return debtToCollateral_ Borrower debt to collateral, which is used in BPF for kicker's reward calculation.
* @return head_ Address of the head auction.
* @return next_ Address of the next auction in queue.
* @return prev_ Address of the prev auction in queue.
*/
function auctionInfo(address borrower_)
external
view
returns (
address kicker_,
uint256 bondFactor_,
uint256 bondSize_,
uint256 kickTime_,
uint256 referencePrice_,
uint256 neutralPrice_,
uint256 debtToCollateral_,
address head_,
address next_,
address prev_
);
/**
* @notice Returns pool related debt values.
* @return debt_ Current amount of debt owed by borrowers in pool.
* @return accruedDebt_ Debt owed by borrowers based on last inflator snapshot.
* @return debtInAuction_ Total amount of debt in auction.
* @return t0Debt2ToCollateral_ t0debt accross all borrowers divided by their collateral, used in determining a collateralization weighted debt.
*/
function debtInfo()
external
view
returns (uint256 debt_, uint256 accruedDebt_, uint256 debtInAuction_, uint256 t0Debt2ToCollateral_);
/**
* @notice Mapping of borrower addresses to `Borrower` structs.
* @dev NOTE: Cannot use appended underscore syntax for return params since struct is used.
* @param borrower_ Address of the borrower.
* @return t0Debt_ Amount of debt borrower would have had if their loan was the first debt drawn from the pool.
* @return collateral_ Amount of collateral that the borrower has deposited, in collateral token.
* @return npTpRatio_ Np to Tp ratio of borrower at the time of last borrow or pull collateral.
*/
function borrowerInfo(address borrower_)
external
view
returns (uint256 t0Debt_, uint256 collateral_, uint256 npTpRatio_);
/**
* @notice Mapping of buckets indexes to `Bucket` structs.
* @dev NOTE: Cannot use appended underscore syntax for return params since struct is used.
* @param index_ Bucket index.
* @return lpAccumulator_ Amount of `LP` accumulated in current bucket.
* @return availableCollateral_ Amount of collateral available in current bucket.
* @return bankruptcyTime_ Timestamp when bucket become insolvent, `0` if healthy.
* @return bucketDeposit_ Amount of quote tokens in bucket.
* @return bucketScale_ Bucket multiplier.
*/
function bucketInfo(uint256 index_)
external
view
returns (
uint256 lpAccumulator_,
uint256 availableCollateral_,
uint256 bankruptcyTime_,
uint256 bucketDeposit_,
uint256 bucketScale_
);
/**
* @notice Mapping of burnEventEpoch to `BurnEvent` structs.
* @dev Reserve auctions correspond to burn events.
* @param burnEventEpoch_ Id of the current reserve auction.
* @return burnBlock_ Block in which a reserve auction started.
* @return totalInterest_ Total interest as of the reserve auction.
* @return totalBurned_ Total ajna tokens burned as of the reserve auction.
*/
function burnInfo(uint256 burnEventEpoch_) external view returns (uint256, uint256, uint256);
/**
* @notice Returns the latest `burnEventEpoch` of reserve auctions.
* @dev If a reserve auction is active, it refers to the current reserve auction. If no reserve auction is active, it refers to the last reserve auction.
* @return Current `burnEventEpoch`.
*/
function currentBurnEpoch() external view returns (uint256);
/**
* @notice Returns information about the pool `EMA (Exponential Moving Average)` variables.
* @return debtColEma_ Debt squared to collateral Exponential, numerator to `TU` calculation.
* @return lupt0DebtEma_ Exponential of `LUP * t0 debt`, denominator to `TU` calculation
* @return debtEma_ Exponential debt moving average.
* @return depositEma_ sample of meaningful deposit Exponential, denominator to `MAU` calculation.
*/
function emasInfo()
external
view
returns (uint256 debtColEma_, uint256 lupt0DebtEma_, uint256 debtEma_, uint256 depositEma_);
/**
* @notice Returns information about pool inflator.
* @return inflator_ Pool inflator value.
* @return lastUpdate_ The timestamp of the last `inflator` update.
*/
function inflatorInfo() external view returns (uint256 inflator_, uint256 lastUpdate_);
/**
* @notice Returns information about pool interest rate.
* @return interestRate_ Current interest rate in pool.
* @return interestRateUpdate_ The timestamp of the last interest rate update.
*/
function interestRateInfo() external view returns (uint256 interestRate_, uint256 interestRateUpdate_);
/**
* @notice Returns details about kicker balances.
* @param kicker_ The address of the kicker to retrieved info for.
* @return claimable_ Amount of quote token kicker can claim / withdraw from pool at any time.
* @return locked_ Amount of quote token kicker locked in auctions (as bonds).
*/
function kickerInfo(address kicker_) external view returns (uint256 claimable_, uint256 locked_);
/**
* @notice Mapping of buckets indexes and owner addresses to `Lender` structs.
* @param index_ Bucket index.
* @param lender_ Address of the liquidity provider.
* @return lpBalance_ Amount of `LP` owner has in current bucket.
* @return depositTime_ Time the user last deposited quote token.
*/
function lenderInfo(uint256 index_, address lender_)
external
view
returns (uint256 lpBalance_, uint256 depositTime_);
/**
* @notice Return the `LP` allowance a `LP` owner provided to a spender.
* @param index_ Bucket index.
* @param spender_ Address of the `LP` spender.
* @param owner_ The initial owner of the `LP`.
* @return allowance_ Amount of `LP` spender can utilize.
*/
function lpAllowance(uint256 index_, address spender_, address owner_) external view returns (uint256 allowance_);
/**
* @notice Returns information about a loan in the pool.
* @param loanId_ Loan's id within loan heap. Max loan is position `1`.
* @return borrower_ Borrower address at the given position.
* @return t0DebtToCollateral_ Borrower t0 debt to collateral.
*/
function loanInfo(uint256 loanId_) external view returns (address borrower_, uint256 t0DebtToCollateral_);
/**
* @notice Returns information about pool loans.
* @return maxBorrower_ Borrower address with highest t0 debt to collateral.
* @return maxT0DebtToCollateral_ Highest t0 debt to collateral in pool.
* @return noOfLoans_ Total number of loans.
*/
function loansInfo()
external
view
returns (address maxBorrower_, uint256 maxT0DebtToCollateral_, uint256 noOfLoans_);
/**
* @notice Returns information about pool reserves.
* @return liquidationBondEscrowed_ Amount of liquidation bond across all liquidators.
* @return reserveAuctionUnclaimed_ Amount of claimable reserves which has not been taken in the `Claimable Reserve Auction`.
* @return reserveAuctionKicked_ Time a `Claimable Reserve Auction` was last kicked.
* @return lastKickedReserves_ Amount of reserves upon last kick, used to calculate price.
* @return totalInterestEarned_ Total interest earned by all lenders in the pool
*/
function reservesInfo()
external
view
returns (
uint256 liquidationBondEscrowed_,
uint256 reserveAuctionUnclaimed_,
uint256 reserveAuctionKicked_,
uint256 lastKickedReserves_,
uint256 totalInterestEarned_
);
/**
* @notice Returns the `pledgedCollateral` state variable.
* @return The total pledged collateral in the system, in WAD units.
*/
function pledgedCollateral() external view returns (uint256);
/**
* @notice Returns the total number of active auctions in pool.
* @return totalAuctions_ Number of active auctions.
*/
function totalAuctionsInPool() external view returns (uint256);
/**
* @notice Returns the `t0Debt` state variable.
* @dev This value should be multiplied by inflator in order to calculate current debt of the pool.
* @return The total `t0Debt` in the system, in `WAD` units.
*/
function totalT0Debt() external view returns (uint256);
/**
* @notice Returns the `t0DebtInAuction` state variable.
* @dev This value should be multiplied by inflator in order to calculate current debt in auction of the pool.
* @return The total `t0DebtInAuction` in the system, in `WAD` units.
*/
function totalT0DebtInAuction() external view returns (uint256);
/**
* @notice Mapping of addresses that can transfer `LP` to a given lender.
* @param lender_ Lender that receives `LP`.
* @param transferor_ Transferor that transfers `LP`.
* @return True if the transferor is approved by lender.
*/
function approvedTransferors(address lender_, address transferor_) external view returns (bool);
}
/**
*
*/
/**
* State Structs **
*/
/**
*
*/
/**
*
*/
/**
* Pool State **
*/
/**
*
*/
/// @dev Struct holding inflator state.
struct InflatorState {
uint208 inflator; // [WAD] pool's inflator
uint48 inflatorUpdate; // [SEC] last time pool's inflator was updated
}
/// @dev Struct holding pool interest state.
struct InterestState {
uint208 interestRate; // [WAD] pool's interest rate
uint48 interestRateUpdate; // [SEC] last time pool's interest rate was updated (not before 12 hours passed)
uint256 debt; // [WAD] previous update's debt
uint256 meaningfulDeposit; // [WAD] previous update's meaningfulDeposit
uint256 t0Debt2ToCollateral; // [WAD] utilization weight accumulator, tracks debt and collateral relationship accross borrowers
uint256 debtCol; // [WAD] previous debt squared to collateral
uint256 lupt0Debt; // [WAD] previous LUP * t0 debt
}
/// @dev Struct holding pool EMAs state.
struct EmaState {
uint256 debtEma; // [WAD] sample of debt EMA, numerator to MAU calculation
uint256 depositEma; // [WAD] sample of meaningful deposit EMA, denominator to MAU calculation
uint256 debtColEma; // [WAD] debt squared to collateral EMA, numerator to TU calculation
uint256 lupt0DebtEma; // [WAD] EMA of LUP * t0 debt, denominator to TU calculation
uint256 emaUpdate; // [SEC] last time pool's EMAs were updated
}
/// @dev Struct holding pool balances state.
struct PoolBalancesState {
uint256 pledgedCollateral; // [WAD] total collateral pledged in pool
uint256 t0DebtInAuction; // [WAD] Total debt in auction used to restrict LPB holder from withdrawing
uint256 t0Debt; // [WAD] Pool debt as if the whole amount was incurred upon the first loan
}
/// @dev Struct holding pool params (in memory only).
struct PoolState {
uint8 poolType; // pool type, can be ERC20 or ERC721
uint256 t0Debt; // [WAD] t0 debt in pool
uint256 t0DebtInAuction; // [WAD] t0 debt in auction within pool
uint256 debt; // [WAD] total debt in pool, accrued in current block
uint256 collateral; // [WAD] total collateral pledged in pool
uint256 inflator; // [WAD] current pool inflator
bool isNewInterestAccrued; // true if new interest already accrued in current block
uint256 rate; // [WAD] pool's current interest rate
uint256 quoteTokenScale; // [WAD] quote token scale of the pool. Same as quote token dust.
}
/**
*
*/
/**
* Buckets State **
*/
/**
*
*/
/// @dev Struct holding lender state.
struct Lender {
uint256 lps; // [WAD] Lender LP accumulator
uint256 depositTime; // timestamp of last deposit
}
/// @dev Struct holding bucket state.
struct Bucket {
uint256 lps; // [WAD] Bucket LP accumulator
uint256 collateral; // [WAD] Available collateral tokens deposited in the bucket
uint256 bankruptcyTime; // Timestamp when bucket become insolvent, 0 if healthy
mapping(address => Lender) lenders; // lender address to Lender struct mapping
}
/**
*
*/
/**
* Deposits State **
*/
/**
*
*/
/// @dev Struct holding deposits (Fenwick) values and scaling.
struct DepositsState {
uint256[8193] values; // Array of values in the FenwickTree.
uint256[8193] scaling; // Array of values which scale (multiply) the FenwickTree accross indexes.
}
/**
*
*/
/**
* Loans State **
*/
/**
*
*/
/// @dev Struct holding loans state.
struct LoansState {
Loan[] loans;
mapping(address => uint256) indices; // borrower address => loan index mapping
mapping(address => Borrower) borrowers; // borrower address => Borrower struct mapping
}
/// @dev Struct holding loan state.
struct Loan {
address borrower; // borrower address
uint96 t0DebtToCollateral; // [WAD] Borrower t0 debt to collateral.
}
/// @dev Struct holding borrower state.
struct Borrower {
uint256 t0Debt; // [WAD] Borrower debt time-adjusted as if it was incurred upon first loan of pool.
uint256 collateral; // [WAD] Collateral deposited by borrower.
uint256 npTpRatio; // [WAD] Np to Tp ratio at the time of last borrow or pull collateral.
}
/**
*
*/
/**
* Auctions State **
*/
/**
*
*/
/// @dev Struct holding pool auctions state.
struct AuctionsState {
uint96 noOfAuctions; // total number of auctions in pool
address head; // first address in auction queue
address tail; // last address in auction queue
uint256 totalBondEscrowed; // [WAD] total amount of quote token posted as auction kick bonds
mapping(address => Liquidation) liquidations; // mapping of borrower address and auction details
mapping(address => Kicker) kickers; // mapping of kicker address and kicker balances
}
/// @dev Struct holding liquidation state.
struct Liquidation {
address kicker; // address that initiated liquidation
uint96 bondFactor; // [WAD] bond factor used to start liquidation
uint96 kickTime; // timestamp when liquidation was started
address prev; // previous liquidated borrower in auctions queue
uint96 referencePrice; // [WAD] used to calculate auction start price
address next; // next liquidated borrower in auctions queue
uint160 bondSize; // [WAD] liquidation bond size
uint96 neutralPrice; // [WAD] Neutral Price when liquidation was started
uint256 debtToCollateral; // [WAD] Borrower debt to collateral, which is used in BPF for kicker's reward calculation
uint256 t0ReserveSettleAmount; // [WAD] Amount of t0Debt that could be settled via reserves in this auction
}
/// @dev Struct holding kicker state.
struct Kicker {
uint256 claimable; // [WAD] kicker's claimable balance
uint256 locked; // [WAD] kicker's balance of tokens locked in auction bonds
}
/**
*
*/
/**
* Reserve Auctions State **
*/
/**
*
*/
/// @dev Struct holding reserve auction state.
struct ReserveAuctionState {
uint256 kicked; // Time a Claimable Reserve Auction was last kicked.
uint256 lastKickedReserves; // [WAD] Amount of reserves upon last kick, used to calculate price.
uint256 unclaimed; // [WAD] Amount of claimable reserves which has not been taken in the Claimable Reserve Auction.
uint256 latestBurnEventEpoch; // Latest burn event epoch.
uint256 totalAjnaBurned; // [WAD] Total ajna burned in the pool.
uint256 totalInterestEarned; // [WAD] Total interest earned by all lenders in the pool.
mapping(uint256 => BurnEvent) burnEvents; // Mapping burnEventEpoch => BurnEvent.
}
/// @dev Struct holding burn event state.
struct BurnEvent {
uint256 timestamp; // time at which the burn event occured
uint256 totalInterest; // [WAD] current pool interest accumulator `PoolCommons.accrueInterest().newInterest`
uint256 totalBurned; // [WAD] burn amount accumulator
}
src/interfaces/pool/commons/IPoolTakerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title Pool Taker Actions
*/
interface IPoolTakerActions {
/**
* @notice Called by actors to use quote token to arb higher-priced deposit off the book.
* @param borrowerAddress_ Address of the borower take is being called upon.
* @param depositTake_ If `true` then the take will happen at an auction price equal with bucket price. Auction price is used otherwise.
* @param index_ Index of a bucket, likely the `HPB`, in which collateral will be deposited.
*/
function bucketTake(address borrowerAddress_, bool depositTake_, uint256 index_) external;
/**
* @notice Called by actors to purchase collateral from the auction in exchange for quote token.
* @param borrowerAddress_ Address of the borower take is being called upon.
* @param maxAmount_ Max amount of collateral that will be taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).
* @param callee_ Identifies where collateral should be sent and where quote token should be obtained.
* @param data_ If provided, take will assume the callee implements `IERC*Taker`. Take will send collateral to
* callee before passing this data to `IERC*Taker.atomicSwapCallback`. If not provided,
* the callback function will not be invoked.
* @return collateralTaken_ Amount of collateral taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).
*/
function take(address borrowerAddress_, uint256 maxAmount_, address callee_, bytes calldata data_)
external
returns (uint256 collateralTaken_);
/**
*
*/
/**
* Reserve Auction **
*/
/**
*
*/
/**
* @notice Purchases claimable reserves during a `CRA` using `Ajna` token.
* @param maxAmount_ Maximum amount of quote token to purchase at the current auction price (`WAD` precision).
* @return amount_ Actual amount of reserves taken (`WAD` precision).
*/
function takeReserves(uint256 maxAmount_) external returns (uint256 amount_);
}
src/interfaces/pool/erc20/IERC20Pool.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {IPool} from "../IPool.sol";
import {IERC20PoolBorrowerActions} from "./IERC20PoolBorrowerActions.sol";
import {IERC20PoolLenderActions} from "./IERC20PoolLenderActions.sol";
import {IERC20PoolImmutables} from "./IERC20PoolImmutables.sol";
import {IERC20PoolEvents} from "./IERC20PoolEvents.sol";
/**
* @title ERC20 Pool
*/
interface IERC20Pool is
IPool,
IERC20PoolLenderActions,
IERC20PoolBorrowerActions,
IERC20PoolImmutables,
IERC20PoolEvents
{
/**
* @notice Initializes a new pool, setting initial state variables.
* @param rate_ Initial interest rate of the pool (min accepted value 1%, max accepted value 10%).
*/
function initialize(uint256 rate_) external;
/**
* @notice Returns the minimum amount of collateral an actor may have in a bucket.
* @param bucketIndex_ The bucket index for which the dust limit is desired, or `0` for pledged collateral.
* @return The dust limit for `bucketIndex_`.
*/
function bucketCollateralDust(uint256 bucketIndex_) external pure returns (uint256);
}
src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title ERC20 Pool Borrower Actions
*/
interface IERC20PoolBorrowerActions {
/**
* @notice Called by borrowers to add collateral to the pool and/or borrow quote from the pool.
* @dev Can be called by borrowers with either `0` `amountToBorrow_` or `0` `collateralToPledge_`, if borrower only wants to take a single action.
* @param borrowerAddress_ The borrower to whom collateral was pledged, and/or debt was drawn for.
* @param amountToBorrow_ The amount of quote tokens to borrow (`WAD` precision).
* @param limitIndex_ Lower bound of `LUP` change (if any) that the borrower will tolerate from a creating or modifying position.
* @param collateralToPledge_ The amount of collateral to be added to the pool (`WAD` precision).
*/
function drawDebt(
address borrowerAddress_,
uint256 amountToBorrow_,
uint256 limitIndex_,
uint256 collateralToPledge_
) external;
/**
* @notice Called by borrowers to repay borrowed quote to the pool, and/or pull collateral form the pool.
* @dev Can be called by borrowers with either `0` `maxQuoteTokenAmountToRepay_` or `0` `collateralAmountToPull_`, if borrower only wants to take a single action.
* @param borrowerAddress_ The borrower whose loan is being interacted with.
* @param maxQuoteTokenAmountToRepay_ The max amount of quote tokens to repay (`WAD` precision).
* @param collateralAmountToPull_ The max amount of collateral to be puled from the pool (`WAD` precision).
* @param recipient_ The address to receive amount of pulled collateral.
* @param limitIndex_ Ensures `LUP` has not moved far from state when borrower pulls collateral.
* @return amountRepaid_ The amount of quote token repaid (`WAD` precision).
*/
function repayDebt(
address borrowerAddress_,
uint256 maxQuoteTokenAmountToRepay_,
uint256 collateralAmountToPull_,
address recipient_,
uint256 limitIndex_
) external returns (uint256 amountRepaid_);
}
src/interfaces/pool/erc20/IERC20PoolEvents.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title ERC20 Pool Events
*/
interface IERC20PoolEvents {
/**
* @notice Emitted when actor adds claimable collateral to a bucket.
* @param actor Recipient that added collateral.
* @param index Index at which collateral were added.
* @param amount Amount of collateral added to the pool (`WAD` precision).
* @param lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).
*/
event AddCollateral(address indexed actor, uint256 indexed index, uint256 amount, uint256 lpAwarded);
/**
* @notice Emitted when borrower draws debt from the pool, or adds collateral to the pool.
* @param borrower The borrower to whom collateral was pledged, and/or debt was drawn for.
* @param amountBorrowed Amount of quote tokens borrowed from the pool (`WAD` precision).
* @param collateralPledged Amount of collateral locked in the pool (`WAD` precision).
* @param lup `LUP` after borrow.
*/
event DrawDebt(address indexed borrower, uint256 amountBorrowed, uint256 collateralPledged, uint256 lup);
}
src/interfaces/pool/erc20/IERC20PoolImmutables.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title ERC20 Pool Immutables
*/
interface IERC20PoolImmutables {
/**
* @notice Returns the `collateralScale` immutable.
* @return The precision of the collateral `ERC20` token based on decimals.
*/
function collateralScale() external view returns (uint256);
}
src/interfaces/pool/erc20/IERC20PoolLenderActions.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
/**
* @title ERC20 Pool Lender Actions
*/
interface IERC20PoolLenderActions {
/**
* @notice Deposit claimable collateral into a specified bucket.
* @param amountToAdd_ Amount of collateral to deposit (`WAD` precision).
* @param index_ The bucket index to which collateral will be deposited.
* @param expiry_ Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.
* @return bucketLP_ The amount of `LP` awarded for the added collateral (`WAD` precision).
*/
function addCollateral(uint256 amountToAdd_, uint256 index_, uint256 expiry_)
external
returns (uint256 bucketLP_);
}
src/interfaces/vault/ILidoWithdrawal.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface ILidoWithdrawal {
// @notice Handles withdrawal request finalization and ETH locking. Requests can be nominal (1:1) or discounted based on share rate.
struct BatchesCalculationState {
uint256 remainingEthBudget;
bool finished;
uint256[36] batches;
uint256 batchesLength;
}
function requestWithdrawalsWstETH(uint256[] calldata _amounts, address _owner)
external
returns (uint256[] memory requestIds);
function claimWithdrawal(uint256 _requestId) external;
function getClaimableEther(uint256[] calldata _requestIds, uint256[] calldata _hints)
external
view
returns (uint256[] memory claimableEthValues);
function getLastCheckpointIndex() external view returns (uint256);
function findCheckpointHints(uint256[] calldata _requestIds, uint256 _firstIndex, uint256 _lastIndex)
external
view
returns (uint256[] memory hintIds);
function finalize(uint256 _lastRequestIdToBeFinalized, uint256 _maxShareRate) external payable;
function prefinalize(uint256[] calldata _batches, uint256 _maxShareRate)
external
view
returns (uint256 ethToLock, uint256 sharesToBurn);
function calculateFinalizationBatches(
uint256 _maxShareRate,
uint256 _maxTimestamp,
uint256 _maxRequestsPerCall,
BatchesCalculationState memory _state
) external view returns (BatchesCalculationState memory);
}
src/interfaces/vault/IWeth.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface IWeth {
function withdraw(uint256 amount) external;
function deposit() external payable;
}
src/interfaces/vault/IWsteth.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
interface IWsteth {
/**
* @notice Returns the amount of stETH that corresponds to one wstETH.
* @dev The value increases over time as staking rewards accumulate.
* @return The amount of stETH per one wstETH, scaled to 18 decimals.
*/
function stEthPerToken() external view returns (uint256);
/**
* @notice Returns the amount of wstETH that corresponds to one stETH.
* @dev This value decreases over time as staking rewards accumulate.
* @return The amount of wstETH per one stETH, scaled to 18 decimals.
*/
function tokensPerStEth() external view returns (uint256);
/**
* @notice Wraps stETH into wstETH.
* @dev Transfers `stETH` from the caller and mints `wstETH` to the caller.
* @param _stETHAmount The amount of stETH to wrap.
* @return The amount of wstETH minted.
*/
function wrap(uint256 _stETHAmount) external returns (uint256);
/**
* @notice Returns the balance of the account.
* @param account The address of the account.
* @return The balance of the account.
*/
function balanceOf(address account) external view returns (uint256);
}
src/libraries/VaultLib.sol
// SPDX-License-Identifier: BUSL-1.1
// Author: Lendvest
pragma solidity ^0.8.20;
import {ILidoWithdrawal} from "../interfaces/vault/ILidoWithdrawal.sol";
/**
* @title VaultLib
*/
library VaultLib {
struct LenderOrder {
address lender;
uint256 quoteAmount;
uint256 vaultShares;
}
struct BorrowerOrder {
address borrower;
uint256 collateralAmount;
}
struct CollateralLenderOrder {
address collateralLender;
uint256 collateralAmount;
}
struct MatchInfo {
address lender;
address borrower;
uint256 quoteAmount; // 97%
uint256 collateralAmount;
uint256 reservedQuoteAmount; // 3%
}
address public constant QUOTE_TOKEN = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant COLLATERAL_TOKEN = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address public constant STETH_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
ILidoWithdrawal public constant LIDO_WITHDRAWAL = ILidoWithdrawal(0x889edC2eDab5f40e902b864aD4d7AdE8E412F9B1);
address public constant router = 0x65Dcc24F8ff9e51F10DCc7Ed1e4e2A61e6E14bd6;
bytes32 public constant donId = 0x66756e2d657468657265756d2d6d61696e6e65742d3100000000000000000000;
uint256 public constant leverageFactor = 80;
/* EVENTS */
event EndEpoch(uint256 time);
event TermEnded(uint256 time);
event FundsQueued(uint256 requestId, uint256 collateralAmount);
event FundsClaimed(uint256 requestId, uint256 amount);
event FundsAdded(uint256 ethAmount, uint256 contractBalance, address sender);
event ForwarderAddressUpdated(address oldAddress, address newAddress);
event AvoidLiquidation(uint256 collateralAmount);
event EpochStarted(uint256 epoch, uint256 epochStart, uint256 termEnd);
event RedemptionRateUpdated(uint256 redemptionRate);
event OCRResponse(bytes32 indexed requestId, bytes response, uint256 rate, bytes err);
event RequestRevertedWithErrorMsg(string reason);
event RequestRevertedWithoutErrorMsg(bytes data);
event LVLidoVaultUtilAddressUpdated(address oldAddress, address newAddress);
event LoanComposition(
uint256 baseCollateral, uint256 leveragedCollateral, uint256 totalCollateral, uint256 quoteToBorrow
);
event AmountsOwed(uint256 lendersOwed, uint256 borrowersOwed, uint256 collateralLendersOwed);
// ------------------------------------------------------------
// Confirmed to be used
event LenderOrderAdded(address lender, uint256 quoteAmount);
event BorrowerOrderAdded(address borrower, uint256 collateralAmount);
event CollateralLenderDeposit(address collateralLender, uint256 collateralAmount);
event WithdrawLender(address lender, uint256 quoteAmount);
event WithdrawBorrower(address borrower, uint256 collateralAmount);
event WithdrawCollateralLender(address collateralLender, uint256 collateralAmount);
event EpochInterestEarned(
uint256 epochNumber,
uint256 lendersInterestAccrued,
uint256 borrowersInterestAccrued,
uint256 collateralLendersInterestAccrued
);
/* Errors */
error InsufficientFunds();
error Unauthorized();
error OnlyForwarder();
error OnlyProxy();
error ReentrantCall();
error InvalidInput();
error NoETHToClaim();
error NoUnfilledOrdersFound();
error MaxFundsExceeded();
error TokenOperationFailed();
error LockedBonds();
error InvalidEpoch();
error EpochNotEnded();
error EmergencyWithdrawalTooEarly();
error NoEmergencyClaim();
// ------------------------------------------------------------
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@chainlink/contracts/=lib/chainlink/contracts/",
"forge-std/=lib/forge-std/src/",
"@prb/math/=lib/prb-math/src/",
"@balancer-labs/=lib/balancer-v2-monorepo/../../node_modules/@balancer-labs/",
"balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
"chainlink/=lib/chainlink/",
"ds-test/=lib/balancer-v2-monorepo/../../pvt/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"prb-math/=lib/prb-math/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.