Verified contractExactUNLICENSED
IdleCDOEpochVariant
Address0x67f839a44e8b6d2cd403d9cb14f3862f2b85e9f8
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.10
- Same code
Only this contract
Details
- Compiler
- solc 0.8.10+commit.fc410830
- Language
- solidity
- Optimization
- Yes, 1 runs
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,027,304
- Creation transaction
- 0x71a651ab27…bc813d9871
27 files
- contracts/IdleCDOEpochVariant.solmain50.39 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol3.11 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.68 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol13.49 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.75 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol716 B
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol3.81 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol7.1 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol12.85 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/utils/Context.sol962 B
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol3.53 KB
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol1.29 KB
- contracts/GuardedLaunchUpgradable.sol3.52 KB
- contracts/IdleCDOCreditVault.sol27.72 KB
- contracts/IdleCDOStorage.sol6.32 KB
- contracts/IdleCDOTranche.sol1.27 KB
- contracts/interfaces/IERC20Detailed.sol363 B
- contracts/interfaces/IIdleCDOStrategy.sol884 B
- contracts/interfaces/IProgrammableBorrower.sol1.73 KB
- contracts/interfaces/keyring/IKeyring.sol170 B
- contracts/strategies/idle/IdleCreditVault.sol47.94 KB
contracts/IdleCDOEpochVariant.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
import {IdleCDOCreditVault} from "./IdleCDOCreditVault.sol";
import {IKeyring} from "./interfaces/keyring/IKeyring.sol";
import {IProgrammableBorrower} from "./interfaces/IProgrammableBorrower.sol";
import {IdleCreditVault} from "./strategies/idle/IdleCreditVault.sol";
error NotAllowed();
/// @title IdleCDO variant that supports epochs.
/// @dev When epoch is running no deposits or withdrawals are allowed. When epoch ends
/// lenders can request withdrawals, that will be fullfilled by the end of the next epoch.
/// If the apr for the new epoch is lower than the last one, lenders can request 'instant'
/// withdrawals that will be fullfilled when the epoch starts and after instantWithdrawDelay (3 days).
/// Funds for instant and normal withdrawals are sent to the strategy contract (IdleCreditVault)
/// @custom:oz-upgrades-unsafe-allow missing-initializer
contract IdleCDOEpochVariant is IdleCDOCreditVault {
/// @notice flag to check if epoch is running
bool public isEpochRunning;
/// @notice flag to allow AA withdraw requests
bool public allowAAWithdrawRequest;
/// @notice flag to allow BB withdraw requests
bool public allowBBWithdrawRequest;
/// @notice duration of the epoch
uint256 public epochDuration;
/// @notice delay to allow instant withdraw requests after next epoch starts
uint256 public instantWithdrawDelay;
/// @notice expected interest for the current epoch
uint256 public expectedEpochInterest;
/// @notice end date of the current epoch
uint256 public epochEndDate;
/// @notice deadline to allow instant withdraw requests
uint256 public instantWithdrawDeadline;
/// @notice apr of the last epoch, unscaled
uint256 public lastEpochApr;
/// @notice min apr change to trigger instant withdraw
uint256 public instantWithdrawAprDelta;
/// @notice fees from pending withdraw request for the curr epoch
uint256 public pendingWithdrawFees;
/// @notice net underlyings gained last epoch
uint256 public lastEpochInterest;
/// @notice flag to allow instant withdraws
bool public allowInstantWithdraw;
/// @notice flag to completely disable instant withdraw
bool public disableInstantWithdraw;
/// @notice flag to check if borrower defaulted
bool public defaulted;
/// @notice Keyring wallet checker address
address public keyring;
/// @notice keyring policyId
uint256 public keyringPolicyId;
/// @notice time between 2 epochs, can be set to 0 to start the next epoch without waiting a specified time
uint256 public bufferPeriod;
/// @dev Deprecated storage slot. Do not remove: kept to preserve the upgradeable storage layout.
bool internal keyringAllowWithdraw;
/// @notice amount of over/under performance that withdrawal requests will cause
int256 internal interestForOverUnderPerformance;
/// @notice flag to disable deposits during an epoch
bool public isDepositDuringEpochDisabled;
/// @notice flag to mint interest as strategy tokens without moving underlyings
bool public isInterestMinted;
event AccrueInterest(uint256 interest, uint256 fees);
event BorrowerDefault(uint256 funds);
function _additionalInit() internal virtual override {
// all yield to senior
isAYSActive = false;
// set epoch params
epochDuration = 30 days;
bufferPeriod = 5 days;
// we set epochEndDate to avoid issues with the first epoch, so we set
// it to current time minus bufferPeriod so that the first epoch can start right away
epochEndDate = block.timestamp - 5 days;
// allow requests for withdrawals
allowAAWithdrawRequest = true;
allowBBWithdrawRequest = true;
// default no instant withdraw allowed
disableInstantWithdraw = true;
// by default deposits during an epoch are disabled
isDepositDuringEpochDisabled = true;
// scale the apr to include the buffer period
_setScaledApr(_getStrategyApr());
}
/// @notice Check if msg sender is owner or manager
function _checkOnlyOwnerOrManager() internal view {
_checkNotAllowed(msg.sender != owner() && msg.sender != IdleCreditVault(strategy).manager());
}
/// @notice Revert if condition is true
/// @param _revertCondition condition to check
function _checkNotAllowed(bool _revertCondition) internal pure {
if (_revertCondition) revert NotAllowed();
}
/// @notice Ensure programmable borrowers are only used with minted-interest accounting.
/// @dev Programmable borrower flows assume minted interest and do not support instant funding.
function _checkProgrammableBorrowerMode() internal view {
_checkNotAllowed(isProgrammableBorrower && (!isInterestMinted || _pendingInstant() != 0));
}
///
/// Only owner or manager methods
///
/// @notice update epoch duration
/// @dev IMPORTANT: bufferPeriod should not be changed once set otherwise interest calculations will be wrong
/// @param _epochDuration duration in seconds
/// @param _bufferPeriod time between 2 epochs
function setEpochParams(uint256 _epochDuration, uint256 _bufferPeriod) public {
_checkOnlyOwnerOrManager();
// cannot set epoch params if epoch is running
// cannot set epochDuration to 0 as it's reserved for closing the pool
// and cannot set epochDuration if previously was set to 0 as borrower repaid all funds
_checkNotAllowed(defaulted || isEpochRunning || _epochDuration == 0 || epochDuration == 0);
epochDuration = _epochDuration;
bufferPeriod = _bufferPeriod;
}
/// @notice update instant withdraw params
/// @param _delay delay in seconds
/// @param _aprDelta min apr delta to trigger instant withdraw
/// @param _disable flag to disable instant withdraw
function setInstantWithdrawParams(uint256 _delay, uint256 _aprDelta, bool _disable) public virtual {
_checkOnlyOwnerOrManager();
_checkNotAllowed(paused());
instantWithdrawDelay = _delay;
instantWithdrawAprDelta = _aprDelta;
disableInstantWithdraw = _disable;
}
/// @notice update keyring address
/// @param _keyring address of the keyring contract
/// @param _keyringPolicyId policyId to check for wallet
function setKeyringParams(address _keyring, uint256 _keyringPolicyId) external {
_checkOnlyOwnerOrManager();
keyring = _keyring;
keyringPolicyId = _keyringPolicyId;
}
/// @notice set flag to disable deposits during an epoch
/// @param _isDisabled true to disable deposits during an epoch
function setIsDepositDuringEpochDisabled(bool _isDisabled) external {
_checkOnlyOwnerOrManager();
isDepositDuringEpochDisabled = _isDisabled;
}
/// @notice Skim raw donated underlyings before forcing accounting.
/// @dev Prevents unsolicited transfers from being crystallized as tranche gains by manual accounting.
function updateAccounting() external override {
_checkOnlyOwnerOrGuardian();
_skimDonatedAssets();
_forceUpdateAccounting();
}
/// @notice set flag to mint interest as strategy tokens without moving underlyings
/// @dev Programmable borrowers always require minted-interest accounting.
/// @param _isMinted true to mint interest instead of transferring underlyings
function setIsInterestMinted(bool _isMinted) external {
_checkOnlyOwner();
_checkNotAllowed(!_isMinted && isProgrammableBorrower);
isInterestMinted = _isMinted;
}
/// @notice Set whether the current strategy borrower should be treated as programmable.
/// @dev This is configured explicitly instead of inferring from code size so contract borrowers
/// such as Safe wallets are not misclassified. The flag cannot be changed while an epoch is live.
/// @param _isProgrammable true to enable programmable-borrower hooks and accounting
function setIsProgrammableBorrower(bool _isProgrammable) external {
_checkOnlyOwner();
_checkNotAllowed(isEpochRunning);
isProgrammableBorrower = _isProgrammable;
}
/// @notice Finalize a hard-default recovery and crystallize the realized loss on tranche prices.
/// @dev `_recoverySource` must approve the strategy for `_recoveredAmount`. Recovered funds are sent
/// directly to the strategy recovery reserve so they do not inflate CDO NAV before finalization.
/// Finalization is one-time and cannot be topped up through this recovery path. Any raw underlying
/// held by the CDO is treated as a donation and sent to `feeReceiver` before recovery is calculated.
/// Recovery uses one aggregate multiplier and does not preserve AA seniority. Before applying
/// that multiplier, active gross backing is split by saved NAV and active default interest uses
/// the configured AA/BB APR split, matching the tranche-specific interest in fixed-APR receipts.
/// A zero or subprecision aggregate recovery finalizes at price zero so tranche prices expose the
/// full loss and pending receipts can be cleared without a payout.
/// @param _recoveredAmount amount of underlying recovered for active LPs and defaulted receipts
/// @param _recoverySource address that supplies the recovered underlying
function finalizeDefault(uint256 _recoveredAmount, address _recoverySource) external {
_checkOnlyOwnerOrManager();
// Send raw CDO underlying to feeReceiver as donated assets; recovery must enter through the strategy.
_skimDonatedAssets();
// Recovery math and reserve accounting live in the strategy where receipt claims are paid.
uint256 defaultBBNav = IdleCreditVault(strategy).finalizeDefaultRecovery(_recoveredAmount, _recoverySource);
// Default recovery should not keep accruing fees or leave old fee claims senior to LP recovery.
fee = 0;
managementFee = 0;
unclaimedFees = 0;
latestHarvestBlock = block.timestamp;
// The strategy returns BB's final recovered active NAV. Writing both final NAVs directly
// makes hard default the sole exception to the ordinary BB-first loss waterfall.
lastNAVBB = defaultBBNav;
lastNAVAA = _contractTokenBalance(strategyToken) - defaultBBNav;
// Crystallize the strategy-token rebalance so virtualPrice/tranchePrice expose the realized loss.
_forceUpdateAccounting();
expectedEpochInterest = 0;
pendingWithdrawFees = 0;
allowAAWithdrawRequest = true;
allowBBWithdrawRequest = true;
// This flag gates claimInstantWithdrawRequest. New instant requests stay disabled below.
allowInstantWithdraw = true;
disableInstantWithdraw = true;
epochDuration = 0;
epochEndDate = 0;
_setScaledApr(0);
}
/// @notice Start the epoch. No deposits or withdrawals are allowed after this.
/// @dev We calculate the total funds that the borrower should return at the end of the epoch
/// ie interests + fees from normal withdraw requests. We send to the borrower underlyings amounts ie interests +
/// new deposits - instant withdraw requests if any. If funds are not enough to satisfy all requests
/// then borrower should return the difference before instantWithdrawDeadline. After epoch start there
/// should be no underlyings in this contract
function startEpoch() external {
_checkOnlyOwnerOrManager();
// Check that buffer period passed (and epoch is not running as epochEndDate is set)
// and that the pool is not closed (ie epochDuration == 0)
uint256 _epochDuration = epochDuration;
_checkNotAllowed(defaulted || block.timestamp < (epochEndDate + bufferPeriod) || _epochDuration == 0);
_checkProgrammableBorrowerMode();
// Remove raw donated underlyings before calculating epoch interest or borrower transfer amounts.
_skimDonatedAssets();
isEpochRunning = true;
// prevent deposits
_pause();
// prevent withdrawals requests
allowAAWithdrawRequest = false;
allowBBWithdrawRequest = false;
IdleCreditVault _strategy = IdleCreditVault(strategy);
// calculate expected interest
// NOTE: all withdrawal requests, burn tranche tokens and decrease getContractValue,
// this can be done only prior to the start of the epoch so getContractValue() is the total amount net
// of all withdrawal requests. We add the fee that we should get for normal pending withdraws
// we also add/remove the over/under performance caused by withdraw requests.
// Pending fees remain due even if fixed-APR requests exhaust active interest.
int256 adjustedActiveInterest = int256(_calcInterest(getContractValue())) + interestForOverUnderPerformance;
if (adjustedActiveInterest < 0) adjustedActiveInterest = 0;
expectedEpochInterest = pendingWithdrawFees + uint256(adjustedActiveInterest);
interestForOverUnderPerformance = 0;
// set expected epoch end date
epochEndDate = block.timestamp + _epochDuration;
// set instant withdraw deadline
instantWithdrawDeadline = block.timestamp + instantWithdrawDelay;
// transfer in this contract funds from interest payment (if any) and buffer deposits sent to the strategy
uint256 _totEpochDeposits = _strategy.totEpochDeposits();
// If interest is minted we do not transfer interest to the strategy
uint256 _toSend = isInterestMinted ? _totEpochDeposits : lastEpochInterest + _totEpochDeposits;
_strategy.sendInterestAndDeposits(_toSend);
// we should first check if there are *instant* redeem requests pending
// and if yes we should send as much underlyings as possible to the IdleCreditVault contract
// if there is any surplus then we send those to the borrower
uint256 pendingInstant = _pendingInstant();
uint256 totUnderlyings = _contractTokenBalance(token);
uint256 _pendingWithdraws = _strategy.pendingWithdraws();
_strategy.collectInstantWithdrawFunds(pendingInstant > totUnderlyings ? totUnderlyings : pendingInstant);
// if there are more requests than the current underlyings we simply send all underlyings
// to the IdleCreditVault contract
if (pendingInstant > totUnderlyings) {
// if borrower is programmable, notify epoch start even if no funds were sent
_startEpochProgrammableBorrower(_pendingWithdraws);
return;
}
// allow instant withdraws right away without waiting for the deadline
allowInstantWithdraw = true;
// and transfer the surplus to the borrower
uint256 _toBorrower = totUnderlyings - pendingInstant;
try this.sendFundsToBorrower(_toBorrower) {
// funds transferred correctly
_startEpochProgrammableBorrower(_pendingWithdraws);
} catch {
// The borrower did not receive the funds, so keep the strategy-token backing in the strategy.
_transferUnderlyings(address(_strategy), _toBorrower);
_strategy.reserveDefaultRecovery(_toBorrower);
_handleBorrowerDefault(_toBorrower);
}
}
/// @notice workaround to have safeTransfer to borrower as external and use it in a try/catch block
/// @param _amount Amount of underlyings to transfer
function sendFundsToBorrower(uint256 _amount) external {
_checkNotAllowed(msg.sender != address(this));
_transferUnderlyings(_borrower(), _amount);
}
/// @notice Stop epoch, accrue interest to the vault and get funds to fullfill normal
/// (ie non-instant) withdraw requests from the prev epoch.
/// @param _newApr New apr to set for the next epoch
/// @param _interest Interest gained in the epoch. This will overwrite the expected interest
/// must be 0 if there is no need to overwrite the expected interest and if > 0 then it should
/// be greater than the pending withdraw fees and newApr must be 0. If `_interest` is 1 then
/// it is interpreted as a special case where we request everything back from the borrower.
/// Programmable borrowers only support `_interest` values `0` and `1`.
/// @dev Only owner or manager can call this function. Borrower MUST approve this contract
function stopEpoch(uint256 _newApr, uint256 _interest) public {
_stopEpoch(_newApr, _interest, 0);
}
/// @notice Internal stop-epoch implementation with optional proportional pending-receipt loss.
/// @param _newApr New apr to set for the next epoch
/// @param _interest Interest gained in the epoch
/// @param _lossAmount Loss amount to split between active LPs and pending receipts
function _stopEpoch(uint256 _newApr, uint256 _interest, uint256 _lossAmount) private {
_checkOnlyOwnerOrManager();
bool _isRequestingAllFunds = _interest == 1;
_checkProgrammableBorrowerMode();
IdleCreditVault _strategy = IdleCreditVault(strategy);
uint256 _pendingWithdrawFees = pendingWithdrawFees;
_checkNotAllowed(
// Check that epoch is running
!isEpochRunning ||
// Check that end date is passed
block.timestamp < epochEndDate ||
// Check that there are no pending instant withdraws, ie `getInstantWithdrawFunds` was called
// before closing the epoch
_pendingInstant() != 0 ||
// Check that overridden interest, if passed (ie > 1), is greater than pending withdraw fees and the apr is 0
// otherwise withdrawal requests may not be fullfilled as they consider also the interest gained in the next epoch
(_interest > 1 && (_interest < _pendingWithdrawFees || _newApr != 0)) ||
// Closing already recalls all principal, so applying a separate loss burn would strand returned cash.
(_isRequestingAllFunds && _lossAmount != 0)
);
uint256 _totBorrowed = _beforeStopEpoch(_isRequestingAllFunds);
// we check if there are donated assets to the pool and transfer them to the feeReceiver if any
_skimDonatedAssets();
_interest = _resolveStopEpochInterest(_interest);
// Base interest for stopEpoch: explicit override (>1) or precomputed expected epoch interest.
uint256 _expectedInterest;
// Strategy finalizes APR0 bucket state and returns adjusted stopEpoch values.
(_expectedInterest, _pendingWithdrawFees) = _strategy.prepareStopEpochWithApr0(_interest);
// Pending withdraws may be increased during APR0 settlement, so read after prepareStopEpochWithApr0.
uint256 _pendingWithdraws = _strategy.pendingWithdraws();
// special case where we get everything back from the borrower
if (_isRequestingAllFunds) {
// Recall gross strategy-token principal, including fee backing excluded from net CDO NAV.
// Prefunded variants also add queue deposits already sent directly to the borrower.
_totBorrowed += _contractTokenBalance(strategyToken);
_expectedInterest += _totBorrowed;
}
uint256 _grossInterest = _isRequestingAllFunds ? _expectedInterest - _totBorrowed : _expectedInterest;
bool _mintInterest = isInterestMinted && !_isRequestingAllFunds;
// In minted mode IdleCDO only needs cash for withdraw requests, not for epoch interest itself.
uint256 _amountToPullFromBorrower = _mintInterest ? 0 : _expectedInterest;
if (_mintInterest && _interest > 1) {
uint256 _maxApr = _strategy.maxApr();
_checkNotAllowed(_maxApr != 0 && _grossInterest > _calcInterestWithApr(getContractValue(), _maxApr) + _pendingWithdrawFees);
}
// Checkpoint management fees before borrower funds are pulled in so the elapsed-period
// accrual applies only to the pre-stop live NAV, not to newly received epoch interest.
_accrueManagementFee();
// Persist only resolved epoch interest for recovery accounting. In close-pool mode `_interest == 1`
// is a sentinel: `_grossInterest` excludes the principal added to `_expectedInterest` above.
expectedEpochInterest = _grossInterest;
pendingWithdrawFees = _pendingWithdrawFees;
// Pending receipts have no tranche identity, so their aggregate loss is pro rata across all
// receipts. The remaining active loss is applied BB-first after the stop succeeds.
(_pendingWithdraws, _lossAmount) = _strategy.previewLossAdjustedWithdrawFunds(_lossAmount);
if (isProgrammableBorrower) {
// Ask the programmable borrower to recall ERC4626 liquidity before IdleCDO pulls funds.
// Hook reverts bubble so transient ERC4626 liquidity failures can be retried.
if (!IProgrammableBorrower(_borrower()).onStopEpoch(_amountToPullFromBorrower + _pendingWithdraws, _isRequestingAllFunds)) {
// Emit the exact cash liability requested from the borrower, including recalled principal
// in close-pool mode and excluding interest fronted through minted accounting.
_handleBorrowerDefault(_amountToPullFromBorrower + _pendingWithdraws);
return;
}
}
// accrue interest to idleCDO, this will increase tranche prices.
// Send also tot withdraw requests amount to the IdleCreditVault contract
try this.getFundsFromBorrower(_amountToPullFromBorrower + _pendingWithdraws) {
// transfer in strategy and decrease pendingWithdraws
_strategy.collectWithdrawFunds(_pendingWithdraws);
// Only settle borrower interest when CDO is fronting it (minted mode, not closing pool).
// When requesting all funds (_interest == 1) the CDO pulls cash directly, no fronting.
if (_mintInterest && isProgrammableBorrower) {
IProgrammableBorrower(_borrower()).settleBorrowerInterest();
}
// Split pending withdraw fees before update accounting
// NOTE: Fees are sent with 2 different transfer calls, here and after updateAccounting, to avoid complicated calculations
if (!_mintInterest) {
_transferFeeUnderlyings(_pendingWithdrawFees);
}
if (_isRequestingAllFunds) {
// we already have strategyTokens equal to _totBorrowed in this contract
// so we transfer _totBorrowed to the strategy to avoid double counting for getContractValue
_transferUnderlyings(address(_strategy), _totBorrowed);
}
if (_mintInterest) {
// if interest is not transferred we mint strategy tokens equal to the full epoch interest
if (_grossInterest != 0) _strategy.mintStrategyTokens(_grossInterest);
// and increase unclaimedFees by pending withdraw fees before _updateAccounting
unclaimedFees += _pendingWithdrawFees;
}
// update tranche prices and unclaimed fees
_updateAccounting();
// transfer fees
uint256 _fees = unclaimedFees;
if (_mintInterest) {
// If interest is minted then we mint new shares for fee receivers instead of transferring underlyings
if (_fees != 0) {
uint256 feeReceiverAmount = _feeReceiverAmount(_fees);
if (feeReceiverAmount != 0) {
_mintSharesAtCurrPrice(feeReceiverAmount, feeReceiver, AATranche);
}
_mintSharesAtCurrPrice(_fees - feeReceiverAmount, owner(), AATranche);
_updateSplitRatio(_getAARatio(true));
}
} else {
// Cash-funded fees can only use gross interest not already owed to pending withdrawals.
uint256 _availableForFees = _grossInterest > _pendingWithdrawFees ? _grossInterest - _pendingWithdrawFees : 0;
if (_fees > _availableForFees) {
_fees = _availableForFees;
}
_transferFeeUnderlyings(_fees);
}
// Any fee that cannot be paid in cash remains accrued and continues reducing NAV.
unclaimedFees -= _fees;
uint256 _totalFees = _fees + (_mintInterest ? 0 : _pendingWithdrawFees);
// save net gain (this does not include interest gained for pending withdrawals)
uint256 netInterest = _grossInterest > _totalFees ? _grossInterest - _totalFees : 0;
lastEpochInterest = netInterest;
// mint strategyTokens equal to interest and send underlying to strategy to avoid double counting for NAV
_strategy.deposit(_mintInterest ? 0 : netInterest);
// save last apr, unscaled
lastEpochApr = _strategy.unscaledApr();
// set apr for next epoch
_setScaledApr(_newApr);
// stop epoch
isEpochRunning = false;
expectedEpochInterest = 0;
pendingWithdrawFees = 0;
if (!skipDefaultCheck) {
// Reopen ordinary deposits and requests only when operations were not explicitly shut down.
_unpause();
allowAAWithdrawRequest = true;
allowBBWithdrawRequest = true;
}
// block instant withdraws claims as these can be done only after the deadline
// or only if borrower is repaying all funds
allowInstantWithdraw = _isRequestingAllFunds;
if (_isRequestingAllFunds) {
// user will request only normal withdraw and can claim right after
disableInstantWithdraw = true;
epochDuration = 0;
epochEndDate = 0;
}
emit AccrueInterest(_expectedInterest - _totBorrowed, _totalFees);
if (_lossAmount != 0) {
_strategy.burnStrategyTokens(_lossAmount);
// Realize the active loss immediately through the ordinary BB-first waterfall.
_forceUpdateAccounting();
}
} catch {
// if borrower defaults, prev instant withdraw requests can still be withdrawn
// as were already fullfilled prior to the default (all funds already sent to the strategy)
_handleBorrowerDefault(_amountToPullFromBorrower + _pendingWithdraws);
}
}
/// @notice Stop epoch and set new duration
/// @dev see stopEpoch and setEpochParams for more details, bufferPeriod is not modified
/// Loss accounting policy for `_lossAmount`:
/// - pending receipts share the pending portion of the loss pro rata because tranche identity is not stored
/// - the remaining active-position loss uses the ordinary BB-first tranche waterfall
/// - hard borrower defaults instead apply one aggregate recovery multiplier to active and pending claims
/// - if `stopEpoch` defaults (`defaulted = true`), the post-stop loss burn and epoch updates are skipped,
/// but variant hooks still run so prefunded queues can settle deposits already sent to the borrower
/// @param _newApr New apr to set for the next epoch
/// @param _interest Interest gained in the epoch
/// @param _duration New epoch duration
/// @param _lossAmount Amount of strategy tokens to burn as realized loss
function stopEpochWithDuration(uint256 _newApr, uint256 _interest, uint256 _duration, uint256 _lossAmount) public {
// stop epoch checks that msg.sender is allowed
_stopEpoch(_newApr, _interest, _lossAmount);
if (_interest != 1 && !defaulted) {
// buffer period is not changed
setEpochParams(_duration, bufferPeriod);
// scale the apr with the new duration and buffer
_setScaledApr(_newApr);
}
_afterStopEpochWithDuration();
}
/// @notice Hook called before stopping an epoch.
/// @dev The base variant has no external principal and returns zero. The prefunded variant
/// overrides this hook to guard direct stops and include principal already sent to the borrower.
/// @param _isClosing true when this stop recalls all pool principal
/// @return additionalPrincipal principal held outside the CDO strategy-token balance
function _beforeStopEpoch(bool _isClosing) internal view virtual returns (uint256) {}
/// @notice internal function called in stop epoch with duration after doing anything else
function _afterStopEpochWithDuration() internal virtual {}
/// @notice Set the scaled apr for the next epoch
/// @param _newApr New apr to set for the next epoch
function _setScaledApr(uint256 _newApr) internal {
IdleCreditVault(strategy).setAprsWithBuffer(_newApr, epochDuration, bufferPeriod);
}
/// @dev Get funds from borrower through an external self-call so callers can use try/catch.
/// @param _amount Total amount to transfer
function getFundsFromBorrower(uint256 _amount) external {
_checkNotAllowed(msg.sender != address(this));
_transferUnderlyingsFrom(_borrower(), address(this), _amount);
}
/// @notice Get funds from borrower to fullfill instant withdraw requests
/// Manager should call this method after instantWithdrawDeadline (when epoch is running)
/// @dev Instant withdrawals are not supported when a programmable borrower is configured.
function getInstantWithdrawFunds() external {
_checkOnlyOwnerOrManager();
// Check that programmable mode is disabled, the epoch is running and the deadline passed.
_checkNotAllowed(isProgrammableBorrower || !isEpochRunning || block.timestamp < instantWithdrawDeadline);
IdleCreditVault _strategy = IdleCreditVault(strategy);
uint256 _instantWithdraws = _pendingInstant();
// transfer funds for instant withdraw to this contract
try this.getFundsFromBorrower(_instantWithdraws) {
// transfer funds to IdleCreditVault and decrease pendingInstantWithdraws
_strategy.collectInstantWithdrawFunds(_instantWithdraws);
// allow instant withdraws
allowInstantWithdraw = true;
} catch {
_handleBorrowerDefault(_instantWithdraws);
}
}
/// @notice Handle borrower default
function _handleBorrowerDefault(uint256 funds) internal {
defaulted = true;
// Do not reopen instant claims here. They remain disabled when funding is pending;
// successful full funding is the only path that enables them before finalization.
if (isProgrammableBorrower) {
IProgrammableBorrower(_borrower()).onDefault();
}
// deposits should be already prevented
if (!paused()) {
_pause();
}
// stop the current epoch
isEpochRunning = false;
// prevent withdrawals requests
allowAAWithdrawRequest = false;
allowBBWithdrawRequest = false;
emit BorrowerDefault(funds);
}
/// @notice Prevent deposits and redeems for all classes of tranches
function _emergencyShutdown(bool isAAWithdrawAllowed) internal override {
// prevent deposits
if (!paused()) {
_pause();
}
// Preserve AA requests only if they were already open. This keeps a forced mid-epoch loss or
// prior emergency from reopening them, while a normal explicit-loss stop can leave them open.
if (!isAAWithdrawAllowed) {
allowAAWithdrawRequest = false;
}
allowBBWithdrawRequest = false;
// Persist the emergency state and let authorized forced accounting crystallize the loss.
skipDefaultCheck = true;
}
/// @notice allow deposits and redeems for all classes of tranches
/// @dev can be called by the owner only
function restoreOperations() external override {
_checkOnlyOwner();
// Check if the pool was defaulted
_checkNotAllowed(defaulted || priceAA == 0);
skipDefaultCheck = false;
// During an epoch ordinary deposits and withdrawal requests must remain disabled. Clearing
// the emergency flag intentionally restores only the dedicated depositDuringEpoch path.
if (isEpochRunning) return;
if (paused()) {
_unpause();
}
allowAAWithdrawRequest = true;
allowBBWithdrawRequest = true;
}
/// @notice Prevent external unpause while an epoch, emergency shutdown, or hard default is active.
function _beforeUnpause() internal view override {
_checkNotAllowed(defaulted || isEpochRunning || skipDefaultCheck);
}
///
/// User methods
///
/// @notice Deposit funds in the vault. Overrides the parent method and adds a check for wallet
function _deposit(uint256 _amount, address _tranche) internal override whenNotPaused returns (uint256) {
_checkNotAllowed(!isWalletAllowed(msg.sender));
// we check if there are donated assets to the pool and transfer them to the feeReceiver if any
_skimDonatedAssets();
// do the inherited deposit flow
return super._deposit(_amount, _tranche);
}
/// @notice Deposit during an active epoch with prorated interest
/// @param _amount Amount of underlyings
/// @param _tranche Tranche to deposit into
/// @return _minted Amount of tranche tokens minted
function depositDuringEpoch(uint256 _amount, address _tranche) external virtual returns (uint256 _minted) {
_checkTranche(_tranche);
_checkNotAllowed(
(_tranche == BBTranche && !isBBDepositEnabled) ||
isDepositDuringEpochDisabled ||
skipDefaultCheck ||
// programmable borrowers use APR=0 so mid-epoch deposits would dilute existing depositors
isProgrammableBorrower ||
// check if AYS is active as we don't support deposits during epoch in that case
isAYSActive ||
// check if epoch is still running even if not manually stopped yet
!isEpochRunning || block.timestamp >= epochEndDate ||
!isWalletAllowed(msg.sender)
);
if (_amount == 0) {
return _minted;
}
uint256 _trancheTotSupply = _trancheSupply(_tranche);
// Avoid pricing discontinuities for the first mid-epoch deposit in a tranche
_checkNotAllowed(_trancheTotSupply == 0);
_skimDonatedAssets();
// Check that limit is not exceeded after removing skimmable raw donations.
_guarded(_amount);
_updateAccounting();
// Get underlyings from user
_transferUnderlyingsFrom(msg.sender, address(this), _amount);
// interest for the remaining epoch plus the full buffer period
// NOTE: _calcInterest already gives full‑epoch + full‑buffer interest for the whole epoch
// So when a user joins mid‑epoch, we take the fraction of that full‑period interest
// that matches the time they actually remain plus the entire buffer
uint256 buffer = bufferPeriod;
uint256 remaining = epochEndDate - block.timestamp;
uint256 interest = _calcInterest(_amount) *
// the time the depositor actually participates (remaining epoch + full buffer)
(remaining + buffer) /
// the total time baked into the scaled APR (epoch + buffer).
(epochDuration + buffer);
uint256 expectedInt = expectedEpochInterest;
uint256 pendingFees = pendingWithdrawFees;
uint256 trancheExpected;
// existing holders' share of net expected interest for the epoch (pre-deposit)
// (exclude pendingWithdrawFees since they go to fee receivers, not tranche holders)
if (expectedInt > pendingFees) {
trancheExpected = _calcTrancheInterestShare(
_netGainAfterFees(expectedInt - pendingFees, _calculateManagementFee(lastNAVAA + lastNAVBB, remaining)),
_tranche
);
}
// interest this deposit will earn for the tranche over the remaining time (net of fees)
uint256 trancheInterest = _calcTrancheInterestShare(
_netGainAfterFees(interest, _calculateManagementFee(_amount, remaining)),
_tranche
);
// pre-deposit expected final NAV for existing holders.
// This won't ever be zero as we checked _trancheTotSupply and we seed initial NAV at tranche creation
uint256 expectedFinal = _lastSavedNAV(_tranche) + trancheExpected;
// mint at a discounted price so depositor gets principal + its prorated interest at epoch end
// A mid‑epoch depositor should get _amount + trancheInterest at epoch end.
// So they need minted = (amount + trancheInterest) / priceEnd.
// priceEnd = expectedFinal / _trancheTotSupply
// so minted = (amount + trancheInterest) * _trancheTotSupply / expectedFinal
_minted = (_amount + trancheInterest) * _trancheTotSupply / expectedFinal;
_mintShares(_tranche, msg.sender, _minted, _amount);
// update expected epoch interest
expectedEpochInterest += interest;
// mint strategy tokens to this contract
IdleCreditVault(strategy).mintStrategyTokens(_amount);
// transfer underlyings to the borrower
_transferUnderlyings(_borrower(), _amount);
}
/// @notice Request a withdraw from the vault
/// @param _amount Amount of tranche tokens
/// @param _tranche Tranche to withdraw from
/// @return _underlyings Amount of underlyings requested
function requestWithdraw(uint256 _amount, address _tranche) external returns (uint256 _underlyings) {
_checkTranche(_tranche);
_checkNotAllowed(
(_tranche == AATranche ? !allowAAWithdrawRequest : !allowBBWithdrawRequest) ||
!isWalletAllowed(msg.sender)
);
// we check if there are donated assets to the pool and transfer them to the feeReceiver if any
_skimDonatedAssets();
// we trigger an update accounting to check for eventual losses
_updateAccounting();
IdleCreditVault creditVault = IdleCreditVault(strategy);
if (_amount == 0) {
_amount = _userTrancheBal(msg.sender, _tranche);
}
_underlyings = _trancheToUnderlyings(_amount, _tranche);
// Programmable borrower deployments do not support instant withdrawals.
// If apr decresed wrt last epoch, request instant withdraw and burn tranche tokens directly
// we compare unscaled aprs
if (_isInstantWithdrawEnabled()) {
uint256 currentApr = creditVault.unscaledApr();
if (lastEpochApr > (currentApr + instantWithdrawAprDelta)) {
// burn strategy tokens from cdo and mint an equal amount to msg.sender as receipt
creditVault.requestInstantWithdraw(_underlyings, msg.sender);
// burn tranche tokens and decrease NAV
_withdrawOps(_amount, _underlyings, _tranche);
return _underlyings;
}
}
uint256 principal = _underlyings;
(uint256 interest, int256 diff) = _calcInterestWithdrawRequest(_underlyings, _tranche);
uint256 totalFees = _totalWithdrawFees(principal, interest);
// user is requesting principal + interest minus upfront management fee and net performance fee
_underlyings = principal + interest - totalFees;
// add expected fees to pending withdraw fees counter
pendingWithdrawFees += totalFees;
/// if there is an AA withdrawal the overperformance that the amount withdrawed would have generated for BB tranches
/// is saved in interestForOverUnderPerformance. This is used to calculate the interest that should be added to the
/// expectedEpochInterest at the startEpoch.
/// If there is a BB withdrawal this amount is subtracted from the expectedEpochInterest
interestForOverUnderPerformance += diff;
// The receipt is fixed now and leaves live NAV. Charge management fees upfront
// for the time it waits outside live NAV: remaining buffer plus the next epoch.
creditVault.requestWithdraw(_underlyings, msg.sender, principal);
// burn tranche tokens and decrease NAV without interest for the next epoch as it was not yet counted in NAV
_withdrawOps(_amount, principal, _tranche);
}
/// @notice Transfer donated assets to the feeReceiver
function _skimDonatedAssets() internal {
_transferUnderlyings(feeReceiver, _contractTokenBalance(token));
}
/// @notice Calculate the interest of an epoch for the given amount
/// @param _amount Amount of underlyings
function _calcInterest(uint256 _amount) internal view returns (uint256) {
return _calcInterestWithApr(_amount, _getStrategyApr());
}
/// @notice Calculate the interest of an epoch for the given amount and apr
/// @param _amount Amount of underlyings
/// @param _apr Apr used for the calculation
function _calcInterestWithApr(uint256 _amount, uint256 _apr) internal view returns (uint256) {
return _amount * (_apr / 100) * epochDuration / (365 days * ONE_TRANCHE_TOKEN);
}
/// @notice Get current tranches value
/// @param _amount Amount of tranche tokens
/// @param _tranche Tranche to get the value for
/// @return Value of the tranche tokens in underlyings
function _trancheToUnderlyings(uint256 _amount, address _tranche) internal view returns (uint256) {
return _amount * _tranchePrice(_tranche) / ONE_TRANCHE_TOKEN;
}
/// @notice Revert unless an address is one of this vault's tranche tokens.
/// @param _tranche tranche address to validate
function _checkTranche(address _tranche) internal view {
_checkNotAllowed(_tranche != AATranche && _tranche != BBTranche);
}
/// @notice Get borrower address from strategy.
/// @return borrower address
function _borrower() internal view returns (address) {
return IdleCreditVault(strategy).borrower();
}
/// @notice Get pending instant withdraws from strategy.
/// @return pending instant withdraws
function _pendingInstant() internal view returns (uint256) {
return IdleCreditVault(strategy).pendingInstantWithdraws();
}
/// @notice Return whether new requests may use instant-withdraw mode.
/// @dev Child variants can permanently disable instant mode independently of legacy storage.
function _isInstantWithdrawEnabled() internal view virtual returns (bool) {
return !disableInstantWithdraw && !isProgrammableBorrower;
}
/// @notice Calculate the interest of an epoch for a withdraw request
/// @dev to avoid having funds not getting interest during buffer period, the apr
/// set in the stopEpoch is higher than then intended one so it will cover also the buffer period
/// eg epoch = 30 days, buffer = 5 days, then if we want to give 10% apr for all the 35 days then
/// in stop epoch we set the apr to 10% * 35/30 = 11.67%. For this reason people who instead request
/// a withdraw should not get the additional interest for the buffer period because they can withdraw
/// a block after the buffer period starts. So we calculate the interest for the 30 days only,
/// eg. if apr is set to 11.67% and we want to calculate the interest for 30 days at 10% we need to do the
/// the opposite -> 11.67% * 30/35 = 10%
/// @param _amount Amount of underlyings
/// @param _tranche Tranche to withdraw from
/// @return _interest Interest for the given amount and given tranche
/// @return _diff over/under performance that this withdraw will cause to the other tranche
function _calcInterestWithdrawRequest(uint256 _amount, address _tranche) internal view returns (uint256 _interest, int256 _diff) {
uint256 _duration = epochDuration;
if (_duration == 0) {
return (_interest, _diff);
}
uint256 _buffer = bufferPeriod;
// calculate total vault interest (they don't get the interest for the buffer period for withdraw requests so
// we scale it back since _calcInterest is scaling the interest with tht buffer period),
uint256 totInterest = _calcInterest(_managedContractValue()) * _duration / (_duration + _buffer);
// calculate total tranche interest for the whole tranche supply
uint256 totTrancheInterest = _calcTrancheInterestShare(totInterest, _tranche);
// calculate interest for the given tranche and given amount
uint256 _trancheBal = _lastSavedNAV(_tranche);
_interest = _trancheBal == 0 ? 0 : _amount * totTrancheInterest / _trancheBal;
// calculate the interest that the _amount would have received if there was no split ratio (ie interest split based only on tvl).
// This is used to calculate the interest that should be added to the expectedEpochInterest when
// withdrawing an AA tranche or the interest that should be removed from expectedEpochInterest when
// withdrawing a BB tranche
uint256 interestWithoutSplitRatio = _calcInterest(_amount) * _duration / (_duration + _buffer);
// difference between total interest and tranche interest (positive for AA, negative for BB)
_diff = int256(interestWithoutSplitRatio) - int256(_interest);
}
/// @notice Calculate the tranche share of the total interest for the epoch
/// @param _totalInterest Total interest for the epoch (net of fees not meant for tranches)
/// @param _tranche Tranche to get the interest for
function _calcTrancheInterestShare(uint256 _totalInterest, address _tranche) internal view returns (uint256) {
uint256 ratio = trancheAPRSplitRatio;
return _totalInterest * (_tranche == AATranche ? ratio : FULL_ALLOC - ratio) / FULL_ALLOC;
}
/// @notice Apply projected management and performance fees to a positive gain.
function _netGainAfterFees(uint256 _gain, uint256 _managementFee) private view returns (uint256 netGain) {
if (_managementFee >= _gain) return netGain;
// remove mgmt fee and performance fee
_gain -= _managementFee;
return _gain - _gain * fee / FULL_ALLOC;
}
/// @notice Calculate total fees charged on a withdrawal request.
/// @param _principal Principal leaving live NAV.
/// @param _interest Projected interest for the requested principal.
/// @return Total management and performance fees to subtract from principal plus projected interest.
function _totalWithdrawFees(uint256 _principal, uint256 _interest) private view returns (uint256) {
uint256 _mgmtFee = _calculateManagementFee(_principal, _withdrawRequestManagementFeeDuration());
// When interest covers management fees, interest - netGain equals management fee plus performance fee.
return _mgmtFee >= _interest ?
_mgmtFee :
_interest - _netGainAfterFees(_interest, _mgmtFee);
}
/// @notice Get the max amount of underlyings that can be withdrawn by user
/// @param _user User address
/// @param _tranche Tranche to withdraw from
function maxWithdrawable(address _user, address _tranche) external view returns (uint256 currentUnderlyings) {
currentUnderlyings = _trancheToUnderlyings(_userTrancheBal(_user, _tranche), _tranche);
currentUnderlyings -= _calculateManagementFee(currentUnderlyings, block.timestamp - latestHarvestBlock);
// add interest for one epoch
(uint256 interest, ) = _calcInterestWithdrawRequest(currentUnderlyings, _tranche);
// remove upfront management fee and performance fee on the remaining projected interest
currentUnderlyings = currentUnderlyings + interest - _totalWithdrawFees(currentUnderlyings, interest);
}
/// @notice Get the duration used for upfront management fees on withdrawal receipts.
/// @dev Receipts leave live NAV at request time but can be claimed only after the
/// next epoch settles. Requests made during the buffer also pay for the remaining
/// buffer time before that next epoch can start.
/// @return _duration One epoch plus any remaining buffer before the next epoch.
function _withdrawRequestManagementFeeDuration() private view returns (uint256 _duration) {
uint256 bufferEnd = epochEndDate + bufferPeriod;
_duration = epochDuration;
if (block.timestamp < bufferEnd) {
_duration += bufferEnd - block.timestamp;
}
}
/// @notice Write off the deposit, this will be used if the borrower and a lender comes to an off-chain agreement
/// so here we burn tranche tokens, the equivalent amount of strategy tokens. Only the borrower can call this
/// @param _amount Amount of tranche tokens to write off
function writeOffDeposit(uint256 _amount, address _tranche) external {
// only borrower can call this method and only during an epoch, otherwise one should follow the traditional flow
_checkNotAllowed(_borrower() != msg.sender || !isEpochRunning);
_checkTranche(_tranche);
// Remove raw donations so write-off interest math only sees accounted vault value.
_skimDonatedAssets();
// Calculate tranche tokens value with current tranche price
uint256 _underlyings = _trancheToUnderlyings(_amount, _tranche);
// We now calculate how much interest + fee the tranche would have generated in the current epoch
(uint256 interest, int256 diff) = _calcInterestWithdrawRequest(_underlyings, _tranche);
// given that _calcInterestWithdrawRequest returns an interest and diff value meant to be used in requestWithdraw
// it does not include the buffer period but given that the epoch is running expectedEpochInterest was
// calculated with the buffer period included, so we need to scale the interest
uint256 _epochDuration = epochDuration;
// (interest + diff) gives the interest based on tvl as write off debt won't follow senior/junior interest split ratio
// diff is positive for AA and negative for BB (in this case it won't be > of interest)
interest = uint256(int256(interest) + diff) * (_epochDuration + bufferPeriod) / _epochDuration;
// Burn tranche tokens and decrease lastNAV
_withdrawOps(_amount, _underlyings, _tranche);
// Burn strategy tokens and decrease NAV (1:1 with underlyings)
IdleCreditVault(strategy).burnStrategyTokens(_underlyings);
// remove the interest + fee from expectedEpochInterest
expectedEpochInterest -= interest;
}
/// @notice Claim a withdraw request from the vault. Can be done when at least 1 epoch passed
/// since last withdraw request
function claimWithdrawRequest() external {
// underlyings requested, here we check that user waited at least one epoch and that borrower
// did not default upon repayment (old requests can still be claimed)
IdleCreditVault(strategy).claimWithdrawRequest(msg.sender);
}
/// @notice Claim an instant withdraw request from the vault. Can be done when epoch is running
/// as funds will get transferred from borrower when epoch starts
function claimInstantWithdrawRequest() external {
// Check that instant withdraws are available
_checkNotAllowed(!allowInstantWithdraw);
IdleCreditVault(strategy).claimInstantWithdrawRequest(msg.sender);
}
/// @notice Check if wallet is allowed to interact with the contract
/// @param _user User address
/// @return true if wallet is allowed or keyring address is not set
function isWalletAllowed(address _user) public view returns (bool) {
address _keyring = keyring;
return _keyring == address(0) || IKeyring(_keyring).checkCredential(keyringPolicyId, _user);
}
/// @notice Notify a programmable borrower that a new epoch has started.
/// @param _pendingWithdraws Amount reserved for withdraw requests that mature at epoch stop.
function _startEpochProgrammableBorrower(uint256 _pendingWithdraws) internal {
if (isProgrammableBorrower) {
IProgrammableBorrower(_borrower()).onStartEpoch(_pendingWithdraws);
}
}
/// @notice Resolve the stop-epoch interest value, optionally sourcing it from a programmable borrower.
/// @dev Programmable borrowers are always the source of truth for epoch interest.
/// In that mode `_interest` values `0` and `1` both resolve to the realized epoch interest,
/// while `1` still separately signals the close-pool path to the caller.
function _resolveStopEpochInterest(uint256 _interest) internal view returns (uint256 _resolvedInterest) {
if (isProgrammableBorrower) {
_checkNotAllowed(_interest > 1);
return IProgrammableBorrower(_borrower()).totalInterestDueNow();
}
_resolvedInterest = _interest;
}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contracts/GuardedLaunchUpgradable.sol
//SPDX-License-Identifier: Apache 2.0
pragma solidity 0.8.10;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/// @notice This abstract contract is used to add an updatable limit on the total value locked
/// that the contract can have. It also have an emergency method that allows the owner to pull
/// funds into predefined recovery address
/// @dev Inherit this contract and add the _guarded method to the child contract
abstract contract GuardedLaunchUpgradable is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
// ERROR MESSAGES:
error Is0();
error ContractLimitReached();
error NotAuthorized();
// TVL limit in underlying value
uint256 public limit;
// recovery address
address internal governanceRecoveryFund;
/// @param _limit TVL limit. (0 means unlimited)
/// @param _governanceRecoveryFund recovery address
/// @param _owner owner address
function __GuardedLaunch_init(uint256 _limit, address _governanceRecoveryFund, address _owner) internal {
_checkIs0(_governanceRecoveryFund == address(0) || _owner == address(0));
// Initialize inherited contracts
OwnableUpgradeable.__Ownable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
// Initialize state variables
limit = _limit;
governanceRecoveryFund = _governanceRecoveryFund;
// Transfer ownership
transferOwnership(_owner);
}
/// @notice this check should be called inside the child contract on deposits to check that the
/// TVL didn't exceed a threshold
/// @param _amount new amount to deposit
function _guarded(uint256 _amount) internal view {
uint256 _limit = limit;
if (_limit > 0) {
if (getContractValue() + _amount > _limit) revert ContractLimitReached();
}
}
/// @dev Check that the second function is not called in the same tx from the same tx.origin
function _checkOnlyOwner() internal view {
_checkNotAuthorized(owner() != msg.sender);
}
/// @notice abstract method, should return the TVL in underlyings
function getContractValue() public virtual view returns (uint256);
/// @notice set contract TVL limit
/// @param _limit limit in underlying value, 0 means no limit
function _setLimit(uint256 _limit) external {
_checkOnlyOwner();
limit = _limit;
}
/// @notice Emergency method, tokens gets transferred to the governanceRecoveryFund address
/// @param _token address of the token to transfer
/// @param _value amount to transfer
function transferToken(address _token, uint256 _value) external {
_checkOnlyOwner();
IERC20Upgradeable(_token).safeTransfer(governanceRecoveryFund, _value);
}
/// @notice check revert condition and revert with Is0 error
/// @param _revertCondition condition to check
function _checkIs0(bool _revertCondition) internal pure {
if (_revertCondition) revert Is0();
}
/// @notice check revert condition and revert with NotAuthorized error
/// @param _revertCondition condition to check
function _checkNotAuthorized(bool _revertCondition) internal pure {
if (_revertCondition) revert NotAuthorized();
}
}
contracts/IdleCDOCreditVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./interfaces/IIdleCDOStrategy.sol";
import "./interfaces/IERC20Detailed.sol";
import "./GuardedLaunchUpgradable.sol";
import "./IdleCDOTranche.sol";
import "./IdleCDOStorage.sol";
/// @title IdleCDO fork for credit vaults
/// @author Idle Labs Inc.
/// @notice Credit vault specific CDO runtime without legacy tranche/reward methods.
/// @dev Storage layout intentionally matches IdleCDO so existing epoch-vault proxies can upgrade safely.
contract IdleCDOCreditVault is PausableUpgradeable, GuardedLaunchUpgradable, IdleCDOStorage {
using SafeERC20Upgradeable for IERC20Detailed;
// ERROR MESSAGES:
error AlreadyInitialized();
error Default();
error AmountTooHigh();
// Used to prevent initialization of the implementation contract
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
token = address(1);
}
// ###################
// Initializer
// ###################
/// @notice can only be called once
/// @dev Initialize the upgradable contract
/// @param _limit contract value limit, can be 0
/// @param _guardedToken underlying token
/// @param _governanceFund address where funds will be sent in case of emergency
/// @param _owner guardian address (can pause, unpause and call emergencyShutdown)
/// @param _strategy strategy address
/// @param _trancheAPRSplitRatio trancheAPRSplitRatio value
function initialize(
uint256 _limit,
address _guardedToken,
address _governanceFund,
address _owner, // GuardedLaunch args
address,
address _strategy,
uint256 _trancheAPRSplitRatio// for AA tranches, so eg 10000 means 10% interest to AA and 90% BB
) external virtual initializer {
if (token != address(0)) revert AlreadyInitialized();
_checkIs0(_strategy == address(0) || _guardedToken == address(0));
_checkAmountTooHigh(_trancheAPRSplitRatio > FULL_ALLOC);
// Initialize contracts
PausableUpgradeable.__Pausable_init();
// check for _governanceFund and _owner != address(0) are inside GuardedLaunchUpgradable
GuardedLaunchUpgradable.__GuardedLaunch_init(_limit, _governanceFund, _owner);
// Deploy Tranches tokens
address _strategyToken = IIdleCDOStrategy(_strategy).strategyToken();
// get strategy token symbol (eg. idleDAI)
string memory _symbol = IERC20Detailed(_strategyToken).symbol();
// create tranche tokens (concat strategy token symbol in the name and symbol of the tranche tokens)
AATranche = _deployTranche(string("Pareto "), string("p"), _symbol);
BBTranche = _deployTranche(string("Pareto BB "), string("pBB_"), _symbol);
// Set CDO params
token = _guardedToken;
strategy = _strategy;
strategyToken = _strategyToken;
trancheAPRSplitRatio = _trancheAPRSplitRatio;
uint256 _oneToken = 10**(IERC20Detailed(_guardedToken).decimals());
oneToken = _oneToken;
priceAA = _oneToken;
priceBB = _oneToken;
// skipDefaultCheck = false is the default value
// Set allowance for strategy
_allowUnlimitedSpend(_guardedToken, _strategy);
_allowUnlimitedSpend(_strategyToken, _strategy);
guardian = _owner;
isAYSActive = true; // adaptive yield split
minAprSplitAYS = AA_RATIO_LIM_DOWN; // AA tranche will get min 50% of the yield
// Credit vaults reuse this legacy slot as the management-fee checkpoint timestamp.
latestHarvestBlock = block.timestamp;
_additionalInit();
}
/// @notice used by child contracts (cdo variants) if anything needs to be done on/after init
function _additionalInit() internal virtual {}
// ###############
// Public methods
// ###############
/// @notice pausable
/// @dev msg.sender should approve this contract first to spend `_amount` of `token`
/// @param _amount amount of `token` to deposit
/// @return AA tranche tokens minted
function depositAA(uint256 _amount) external returns (uint256) {
return _deposit(_amount, AATranche);
}
/// @notice pausable in _deposit
/// @dev msg.sender should approve this contract first to spend `_amount` of `token`
/// @param _amount amount of `token` to deposit
/// @return BB tranche tokens minted
function depositBB(uint256 _amount) external returns (uint256) {
_checkNotAuthorized(!isBBDepositEnabled);
return _deposit(_amount, BBTranche);
}
// ###############
// Views
// ###############
/// @param _tranche tranche address
/// @return tranche price, in underlyings, at the last interaction (not considering interest earned
/// since last interaction)
function tranchePrice(address _tranche) external view returns (uint256) {
return _tranchePrice(_tranche);
}
/// @notice calculates the current net TVL (in `token` terms)
/// @dev `unclaimedFees` are not counted.
function getContractValue() public override view returns (uint256) {
// Credit vault strategy tokens are minted 1:1 with underlyings and use the same decimals.
return _contractTokenBalance(strategyToken) + _contractTokenBalance(token) - unclaimedFees;
}
/// @notice Calculates the current managed net TVL.
/// @dev Raw underlyings held by the CDO are excluded because unsolicited transfers are skimmed on interactions.
/// @return Strategy-token-backed TVL net of accrued fees.
function _managedContractValue() internal virtual view returns (uint256) {
uint256 strategyTokenBalance = _contractTokenBalance(strategyToken);
uint256 fees = unclaimedFees;
return strategyTokenBalance > fees ? strategyTokenBalance - fees : 0;
}
/// @param _tranche tranche address
/// @return actual apr given current ratio between AA and BB tranches
function getApr(address _tranche) external view returns (uint256) {
uint256 _AATrancheSplitRatio = _getAARatio(false);
uint256 stratApr = _getStrategyApr();
if (_AATrancheSplitRatio == 0 || _AATrancheSplitRatio == FULL_ALLOC) {
// with only one initialized tranche, it receives all apr and the empty tranche receives zero
return (_tranche == AATranche) == (_AATrancheSplitRatio == 0) ? 0 : stratApr;
}
uint256 _trancheAPRSplitRatio = trancheAPRSplitRatio;
if (_tranche != AATranche) {
// BB apr is: stratApr * BBaprSplitRatio / BBSplitRatio -> where
// BBaprSplitRatio is: (FULL_ALLOC - _trancheAPRSplitRatio) and
// BBSplitRatio is: (FULL_ALLOC - _AATrancheSplitRatio)
return stratApr * (FULL_ALLOC - _trancheAPRSplitRatio) / (FULL_ALLOC - _AATrancheSplitRatio);
}
// AA apr is: stratApr * AAaprSplitRatio / AASplitRatio
return stratApr * _trancheAPRSplitRatio / _AATrancheSplitRatio;
}
/// @notice calculates the current AA tranches ratio
/// @dev _virtualBalance is used to have a more accurate/recent value for the AA ratio
/// because it calculates the balance after splitting the accrued interest since the
/// last depositXX/withdrawXX
/// @return AA tranches ratio (in underlying value) considering all interest
function getCurrentAARatio() external view returns (uint256) {
return _getAARatio(false);
}
/// @notice calculates the current tranches price considering the interest/loss that is yet to be splitted
/// ie the interest/loss generated since the last update of priceAA and priceBB (done on depositXX/withdrawXX)
/// @param _tranche address of the requested tranche
/// @return _virtualPrice tranche price considering all interest/losses
function virtualPrice(address _tranche) public virtual view returns (uint256 _virtualPrice) {
(_virtualPrice, ) = _virtualPriceAux(
_tranche,
_managedContractValue(), // nav
lastNAVAA + lastNAVBB, // lastNAV
_lastSavedNAV(_tranche), // lastTrancheNAV
trancheAPRSplitRatio
);
}
// ###############
// Internal
// ###############
/// @notice method used to deposit `token` and mint tranche tokens
/// @dev this contract must be approved to spend at least _amount of `token` before calling this method
/// @param _amount amount of underlyings (`token`) to deposit
/// @param _tranche tranche address
/// @return _minted number of tranche tokens minted
function _deposit(uint256 _amount, address _tranche) internal virtual whenNotPaused returns (uint256 _minted) {
if (_amount == 0) {
return _minted;
}
// check that we are not depositing more than the contract available limit
_guarded(_amount);
// interest accrued since last depositXX/withdrawXX is splitted between AA and BB
// according to trancheAPRSplitRatio. NAVs of AA and BB are updated and tranche
// prices adjusted accordingly
_updateAccounting();
// get underlyings from sender
address _token = token;
uint256 _preBal = _contractTokenBalance(_token);
_transferUnderlyingsFrom(msg.sender, address(this), _amount);
// mint tranche tokens according to the current tranche price
_minted = _mintSharesAtCurrPrice(_contractTokenBalance(_token) - _preBal, msg.sender, _tranche);
// update trancheAPRSplitRatio
_updateSplitRatio(_getAARatio(true));
// direct deposit in the strategy
IIdleCDOStrategy(strategy).deposit(_amount);
}
/// @notice this method is called on depositXX/withdrawXX and
/// updates the accounting of the contract and effectively splits the yield/loss between the
/// AA and BB tranches
/// @dev this method:
/// - update tranche prices (priceAA and priceBB)
/// - update net asset value for both tranches (lastNAVAA and lastNAVBB)
/// - update fee accounting (unclaimedFees)
/// @return shutdown true when a loss exhausted BB or fully wiped an AA-only vault
function _updateAccounting() internal virtual returns (bool shutdown) {
_accrueManagementFee();
uint256 _lastNAVAA = lastNAVAA;
uint256 _lastNAVBB = lastNAVBB;
uint256 _lastNAV = _lastNAVAA + _lastNAVBB;
uint256 nav = getContractValue();
uint256 _aprSplitRatio = trancheAPRSplitRatio;
// If gain is > 0, then collect some fees in `unclaimedFees`
if (nav > _lastNAV) {
unclaimedFees += (nav - _lastNAV) * fee / FULL_ALLOC;
}
(uint256 _priceAA, int256 _totalAAGain) = _virtualPriceAux(AATranche, nav, _lastNAV, _lastNAVAA, _aprSplitRatio);
(uint256 _priceBB, int256 _totalBBGain) = _virtualPriceAux(BBTranche, nav, _lastNAV, _lastNAVBB, _aprSplitRatio);
lastNAVAA = uint256(int256(_lastNAVAA) + _totalAAGain);
lastNAVBB = uint256(int256(_lastNAVBB) + _totalBBGain);
// Ordinary losses exhaust BB before reducing AA. Stop normal interactions once BB is wiped,
// or when an AA-only vault is fully wiped, so the loss must be crystallized explicitly.
if ((_totalBBGain < 0 && -_totalBBGain >= int256(_lastNAVBB)) || (_lastNAV != 0 && nav == 0)) {
shutdown = true;
if (!skipDefaultCheck) revert Default();
// Keep a total wipe distinguishable from an uninitialized vault when no BB NAV existed.
if (nav == 0) _priceAA = 0;
_emergencyShutdown(true);
}
priceAA = _priceAA;
priceBB = _priceBB;
}
/// @notice calculates the NAV for a tranche considering the interest that is yet to be splitted
/// @param _tranche address of the requested tranche
/// @return net asset value, in underlying tokens, for _tranche considering all nav
function _virtualBalance(address _tranche) internal view returns (uint256) {
// balance is: tranche supply * virtual tranche price
return _trancheSupply(_tranche) * virtualPrice(_tranche) / ONE_TRANCHE_TOKEN;
}
/// @notice calculates the NAV for a tranche without considering the interest that is yet to be splitted
/// @param _tranche address of the requested tranche
/// @return net asset value, in underlying tokens, for _tranche
function _instantBalance(address _tranche) internal view returns (uint256) {
return _trancheSupply(_tranche) * _tranchePrice(_tranche) / ONE_TRANCHE_TOKEN;
}
/// @notice gets total supply for a specific tranche
/// @param _tranche address of the requested tranche
function _trancheSupply(address _tranche) internal view returns (uint256) {
return IdleCDOTranche(_tranche).totalSupply();
}
/// @notice gets last saved NAV for a specific tranche
/// @param _tranche address of the requested tranche
function _lastSavedNAV(address _tranche) internal view returns (uint256) {
return _tranche == AATranche ? lastNAVAA : lastNAVBB;
}
/// @notice Calculates the current tranche price and gain or loss since the last accounting update.
/// @dev Gains follow `trancheAPRSplitRatio`; ordinary losses exhaust BB before reducing AA.
/// @param _tranche address of the requested tranche
/// @param _nav current NAV
/// @param _lastNAV last saved NAV
/// @param _lastTrancheNAV last saved tranche NAV
/// @param _trancheAPRSplitRatio APR split ratio for AA tranche
/// @return _virtualPrice tranche price considering all interest
/// @return _totalTrancheGain (int256) tranche gain/loss since last update
function _virtualPriceAux(
address _tranche,
uint256 _nav,
uint256 _lastNAV,
uint256 _lastTrancheNAV,
uint256 _trancheAPRSplitRatio
) internal virtual view returns (uint256 _virtualPrice, int256 _totalTrancheGain) {
// A zero supply identifies a tranche that was never initialized. A non-zero supply with
// zero NAV is an economically wiped tranche and must keep its saved zero price.
uint256 trancheSupply = _trancheSupply(_tranche);
if (trancheSupply == 0) return (oneToken, 0);
if (_lastNAV == 0 && _nav == 0) return (0, 0);
// In order to correctly split the interest generated between AA and BB tranche holders
// (according to the trancheAPRSplitRatio) we need to know how much interest/loss we gained
// since the last price update (during a depositXX/withdrawXX)
// To do that we need to get the current value of the assets in this contract
// and the last saved one (always during a depositXX/withdrawXX)
// Calculate the total gain/loss
int256 totalGain = int256(_nav) - int256(_lastNAV);
// Ordinary zero-delta interactions keep their saved price for compatibility. Forced
// accounting recomputes NAV per share, which is required after discounted mid-epoch deposits.
if (totalGain == 0 && !skipDefaultCheck) return (_tranchePrice(_tranche), 0);
// Remove performance fee for gains
if (totalGain > 0) {
totalGain -= totalGain * int256(fee) / int256(FULL_ALLOC);
}
bool _isAATranche = _tranche == AATranche;
// A class with no saved NAV cannot be revived by later gains. If only this class has saved
// NAV, it receives the full gain or loss; otherwise both classes participate.
if (_lastTrancheNAV == 0) {
_totalTrancheGain = 0;
} else if (_lastNAV == _lastTrancheNAV) {
_totalTrancheGain = totalGain;
} else {
if (totalGain > 0) {
// Split the net gain, according to _trancheAPRSplitRatio, with precision loss favoring the AA tranche.
int256 totalBBGain = totalGain * int256(FULL_ALLOC - _trancheAPRSplitRatio) / int256(FULL_ALLOC);
// The new NAV for the tranche is old NAV + total gain for the tranche
_totalTrancheGain = _isAATranche ? (totalGain - totalBBGain) : totalBBGain;
} else {
int256 maxBBLoss = -int256(lastNAVBB);
int256 totalBBLoss = totalGain > maxBBLoss ? totalGain : maxBBLoss;
_totalTrancheGain = _isAATranche ? totalGain - totalBBLoss : totalBBLoss;
}
}
// Split the new NAV (_lastTrancheNAV + _totalTrancheGain) per tranche token
_virtualPrice = uint256(int256(_lastTrancheNAV) + _totalTrancheGain) * ONE_TRANCHE_TOKEN / trancheSupply;
}
/// @notice mint tranche tokens at current price and updates tranche last NAV
/// @param _amount, in underlyings, to convert in tranche tokens
/// @param _to receiver address of the newly minted tranche tokens
/// @param _tranche tranche address
/// @return _minted number of tranche tokens minted
function _mintSharesAtCurrPrice(uint256 _amount, address _to, address _tranche) internal virtual returns (uint256 _minted) {
// calculate # of tranche token to mint based on current tranche price: _amount / tranchePrice
_minted = _amount * ONE_TRANCHE_TOKEN / _tranchePrice(_tranche);
_mintShares(_tranche, _to, _minted, _amount);
}
/// @notice mint tranche tokens and updates tranche last NAV
/// @param _tranche tranche address
/// @param _to receiver address of the newly minted tranche tokens
/// @param _shares number of tranche tokens to mint
/// @param _underlyings amount of underlyings added to the tranche
function _mintShares(address _tranche, address _to, uint256 _shares, uint256 _underlyings) internal {
IdleCDOTranche(_tranche).mint(_to, _shares);
// update NAV with the _amount of underlyings added
if (_tranche == AATranche) {
lastNAVAA += _underlyings;
} else {
lastNAVBB += _underlyings;
}
}
/// @notice Burn tranche tokens and update NAV and trancheAPRSplitRatio
/// @param _amount Amount of tranche tokens
/// @param _underlyings Amount of underlyings
/// @param _tranche Tranche to withdraw from
function _withdrawOps(uint256 _amount, uint256 _underlyings, address _tranche) internal {
// burn tranche token
IdleCDOTranche(_tranche).burn(msg.sender, _amount);
// update NAV with the _amount of underlyings removed
if (_tranche == AATranche) {
lastNAVAA -= _underlyings;
} else {
lastNAVBB -= _underlyings;
}
// update trancheAPRSplitRatio
_updateSplitRatio(_getAARatio(true));
}
/// @notice updates trancheAPRSplitRatio based on the current tranches TVL ratio between AA and BB
/// @dev the idea here is to limit the min and max APR that the senior tranche can get
function _updateSplitRatio(uint256 tvlAARatio) internal virtual {
uint256 _minSplit = minAprSplitAYS;
_minSplit = _minSplit == 0 ? AA_RATIO_LIM_DOWN : _minSplit;
if (isAYSActive) {
uint256 aux;
if (tvlAARatio >= AA_RATIO_LIM_UP) {
aux = tvlAARatio == FULL_ALLOC ? FULL_ALLOC : AA_RATIO_LIM_UP;
} else if (tvlAARatio > _minSplit) {
aux = tvlAARatio;
} else {
aux = _minSplit;
}
trancheAPRSplitRatio = aux * tvlAARatio / FULL_ALLOC;
}
}
/// @notice calculates the current AA tranches ratio
/// @dev it does count accrued interest not yet split since last
/// depositXX/withdrawXX only if _instant flag is true
/// @param _instant if true, it returns the current ratio without accrued interest
/// @return AA tranches ratio (in underlying value) considering all interest
function _getAARatio(bool _instant) internal view returns (uint256) {
function(address) internal view returns (uint256) _getNAV =
_instant ? _instantBalance : _virtualBalance;
uint256 AABal = _getNAV(AATranche);
uint256 contractVal = AABal + _getNAV(BBTranche);
if (contractVal == 0) {
return 0;
}
// Current AA tranche split ratio = AABal * FULL_ALLOC / (AABal + BBBal)
return AABal * FULL_ALLOC / contractVal;
}
/// @param _tranche tranche address
/// @return last saved tranche price, in underlyings
function _tranchePrice(address _tranche) internal view returns (uint256) {
if (_trancheSupply(_tranche) == 0) {
return oneToken;
}
return _tranche == AATranche ? priceAA : priceBB;
}
/// @notice internal method used to deploy a new tranche token
/// @param _namePrefix prefix for the name of the tranche token
/// @param _symbolPrefix prefix for the symbol of the tranche token
/// @param _symbol suffix for the symbol of the tranche token
/// @return address of the newly deployed tranche token
function _deployTranche(string memory _namePrefix, string memory _symbolPrefix, string memory _symbol) internal returns (address) {
return address(new IdleCDOTranche(_concat(_namePrefix, _symbol), _concat(_symbolPrefix, _symbol)));
}
// ###################
// onlyOwner
// ###################
/// @notice Enable or disable deposits into the BB tranche.
/// @param _enabled true to allow BB deposits
function setBBDepositEnabled(bool _enabled) external {
_checkOnlyOwner();
isBBDepositEnabled = _enabled;
}
/// @param _active flag to allow Adaptive Yield Split
function setIsAYSActive(bool _active) external virtual {
_checkOnlyOwner();
isAYSActive = _active;
}
/// @param _feeReceiver fee receiver address. It gets the portion of fees specified by `_feeSplit`.
/// The remaining fee portion goes to `owner()`.
/// @dev Reverts if `_feeReceiver` is address(0). Use `_feeSplit = 0` to route all fees to `owner()`.
/// @param _fee new performance fee value (in % with 100000 = 100%)
/// @param _feeSplit portion of collected fees sent to `_feeReceiver` (100000 = 100%)
/// @param _managementFee annualized management fee (in % with 100000 = 100%)
function setFeeParams(address _feeReceiver, uint256 _fee, uint256 _feeSplit, uint256 _managementFee) external {
_checkOnlyOwner();
_checkAmountTooHigh(_fee > MAX_FEE || _feeSplit > FULL_ALLOC || _managementFee > MAX_FEE / 10);
_checkIs0((feeReceiver = _feeReceiver) == address(0));
_accrueManagementFee();
fee = _fee;
feeSplit = _feeSplit;
managementFee = _managementFee;
}
/// @param _guardian new guardian (pauser) address
function setGuardian(address _guardian) external {
_checkOnlyOwner();
_checkIs0((guardian = _guardian) == address(0));
}
/// @param _aprSplit min apr split for AA, considering FULL_ALLOC = 100%
function setMinAprSplitAYS(uint256 _aprSplit) external virtual {
_checkOnlyOwner();
_checkAmountTooHigh((minAprSplitAYS = _aprSplit) > FULL_ALLOC);
}
/// @notice this method updates the accounting of the contract and effectively splits the yield/loss between the
/// AA and BB tranches. This can be called at any time as is called automatically on each deposit/redeem. It's here
/// just to be called when a loss exhausted BB, as deposits/redeems are paused, but we need to
/// crystallize the BB-first loss.
function updateAccounting() external virtual {
_checkOnlyOwnerOrGuardian();
_forceUpdateAccounting();
}
/// @notice force accounting update without reverting on default path
function _forceUpdateAccounting() internal {
bool wasSkippingDefaultCheck = skipDefaultCheck;
skipDefaultCheck = true;
// Preserve an existing emergency shutdown and any wipe reported by accounting.
if (!_updateAccounting()) {
skipDefaultCheck = wasSkippingDefaultCheck;
}
}
/// @notice pause deposits and redeems for all classes of tranches
/// @dev can be called by both the owner and the guardian
function emergencyShutdown() external {
_checkOnlyOwnerOrGuardian();
_emergencyShutdown(false);
}
function _emergencyShutdown(bool) internal virtual {}
/// @notice allow deposits and redeems for all classes of tranches
/// @dev can be called by the owner only
function restoreOperations() external virtual {}
/// @notice Pauses deposits
/// @dev can be called by both the owner and the guardian
function pause() external {
_checkOnlyOwnerOrGuardian();
_pause();
}
/// @notice Unpauses deposits
/// @dev can be called by both the owner and the guardian
function unpause() external {
_checkOnlyOwnerOrGuardian();
_beforeUnpause();
_unpause();
}
/// @notice Hook executed before external unpause.
function _beforeUnpause() internal view virtual {}
// ###################
// Helpers
// ###################
/// @dev Check that the msg.sender is the either the owner or the guardian
function _checkOnlyOwnerOrGuardian() internal view {
_checkNotAuthorized(msg.sender != guardian && msg.sender != owner());
}
/// @notice returns the current balance of this contract for a specific token
/// @param _token token address
/// @return balance of `_token` for this contract
function _contractTokenBalance(address _token) internal view returns (uint256) {
return IERC20Detailed(_token).balanceOf(address(this));
}
/// @notice Checkpoint accrued management fees into `unclaimedFees`.
/// @dev Raw underlyings are excluded because unsolicited transfers are skimmed instead of managed.
function _accrueManagementFee() internal {
unclaimedFees += _calculateManagementFee(_managedContractValue(), block.timestamp - latestHarvestBlock);
latestHarvestBlock = block.timestamp;
}
/// @notice calculate annualized management fee for a balance over a duration
function _calculateManagementFee(uint256 _nav, uint256 _duration) internal view returns (uint256) {
// 3153600000000 == FULL_ALLOC * 365 days
return _nav * managementFee * _duration / 3153600000000;
}
/// @notice returns the user tranche balance for a specific tranche
/// @param _user user address
/// @param _tranche tranche address
function _userTrancheBal(address _user, address _tranche) internal view returns (uint256) {
return IERC20Detailed(_tranche).balanceOf(_user);
}
/// @dev Set allowance for _token to unlimited for _spender
/// @param _token token address
/// @param _spender spender address
function _allowUnlimitedSpend(address _token, address _spender) internal {
IERC20Detailed(_token).safeIncreaseAllowance(_spender, type(uint256).max);
}
/// @dev transfer underlyings to a specific address
/// @param _to receiver address
/// @param _amount amount to transfer
function _transferUnderlyings(address _to, uint256 _amount) internal {
if (_amount == 0) return;
IERC20Detailed(token).safeTransfer(_to, _amount);
}
/// @notice transfer fee to feeReceiver and owner according to feeSplit
/// @param _amount total fee amount to split and transfer (in underlyings)
function _transferFeeUnderlyings(uint256 _amount) internal {
uint256 feeReceiverAmount = _feeReceiverAmount(_amount);
_transferUnderlyings(feeReceiver, feeReceiverAmount);
_transferUnderlyings(owner(), _amount - feeReceiverAmount);
}
/// @notice calculates the amount to transfer to feeReceiver based on the feeSplit
/// @dev `setFeeParams` guarantees a nonzero receiver; a zero split naturally returns zero.
/// @param _amount total fee amount to split
function _feeReceiverAmount(uint256 _amount) internal view returns (uint256) {
return _amount * feeSplit / FULL_ALLOC;
}
/// @dev transfer underlyings from a specific address to another address
/// @param _from sender address
/// @param _to receiver address
/// @param _amount amount to transfer
function _transferUnderlyingsFrom(address _from, address _to, uint256 _amount) internal {
if (_amount == 0) return;
IERC20Detailed(token).safeTransferFrom(_from, _to, _amount);
}
/// @dev Get the current strategy apr
function _getStrategyApr() internal view returns (uint256) {
return IIdleCDOStrategy(strategy).getApr();
}
/// @notice concat 2 strings in a single one
/// @param a first string
/// @param b second string
/// @return new string with a and b concatenated
function _concat(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
/// @notice check revert condition and revert with AmountTooHigh error
/// @param _revertCondition condition to check
function _checkAmountTooHigh(bool _revertCondition) internal pure {
if (_revertCondition) revert AmountTooHigh();
}
}
contracts/IdleCDOStorage.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
contract IdleCDOStorage {
// constant to represent 100%
uint256 public constant FULL_ALLOC = 100000;
// max fee, relative to FULL_ALLOC
uint256 internal constant MAX_FEE = 20000;
// one token
uint256 public constant ONE_TRANCHE_TOKEN = 10**18;
// variable used to save the last tx.origin and block.number
bytes32 internal _lastCallerBlock;
// variable used to save the block of the latest harvest
uint256 public latestHarvestBlock;
// WETH address
address internal weth;
// [DEPRECATED] tokens used to incentivize the idle tranche ideal ratio
address[] internal incentiveTokens;
// underlying token (eg DAI)
address public token;
// address that can only pause/unpause the contract in case of emergency
address internal guardian;
// one `token` (eg for DAI 10**18)
uint256 public oneToken;
// address that can call the 'harvest' method and lend pool assets
address internal rebalancer;
// address of the uniswap v2 router
IUniswapV2Router02 internal uniswapRouterV2;
// Flag for allowing AA withdraws
bool internal allowAAWithdraw;
// Flag for allowing BB withdraws
bool internal allowBBWithdraw;
// Flag for allowing to enable reverting in case the strategy gives back less
// amount than the requested one
bool internal revertIfTooLow;
// Flag to enable the `Default Check` (related to the emergency shutdown)
bool internal skipDefaultCheck;
// address of the strategy used to lend funds
address public strategy;
// address of the strategy token which represent the position in the lending provider
address public strategyToken;
// address of AA Tranche token contract
address public AATranche;
// address of BB Tranche token contract
address public BBTranche;
// address for stkIDLE gating for AA tranche. addr(0) -> inactive, addr(1) -> active
address internal AAStaking;
// address for stkIDLE gating for BB tranche. addr(0) -> inactive, addr(1) -> active
address internal BBStaking;
// Apr split ratio for AA tranches
// (relative to FULL_ALLOC so 50% => 50000 => 50% of the interest to tranche AA)
uint256 public trancheAPRSplitRatio; //
// [DEPRECATED] Ideal tranche split ratio in `token` value
// (relative to FULL_ALLOC so 50% => 50000 means 50% of tranches (in value) should be AA)
uint256 internal trancheIdealWeightRatio;
// Price for minting AA tranche, in underlyings
uint256 public priceAA;
// Price for minting BB tranche, in underlyings
uint256 public priceBB;
// last saved net asset value (in `token`) for AA tranches
uint256 public lastNAVAA;
// last saved net asset value (in `token`) for BB tranches
uint256 public lastNAVBB;
// last saved lending provider price
uint256 internal lastStrategyPrice;
// Keeps track of unclaimed fees for fee receivers
uint256 public unclaimedFees;
// Keeps an unlent balance both for cheap redeem and as 'insurance of last resort'
uint256 internal unlentPerc;
// Fee amount (relative to FULL_ALLOC)
uint256 public fee;
// address receiving the feeSplit portion of collected fees
address public feeReceiver;
// [DEPRECATED] trancheIdealWeightRatio ± idealRanges, used in updateIncentives
uint256 internal idealRange;
// period, in blocks, for progressively releasing harvested rewards to users
uint256 internal releaseBlocksPeriod;
// amount of rewards sold in the last harvest (in `token`)
uint256 internal harvestedRewards;
// stkAave address
address internal constant stkAave = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
// aave address
address internal constant AAVE = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9);
// if deposits will be put directly in the strategy
bool internal directDeposit;
// referral address of the strategy developer
address internal referral;
// portion of collected fees sent to feeReceiver. The rest goes to owner()
uint256 public feeSplit;
// if Adaptive Yield Split is active
bool internal isAYSActive;
// constant to represent 99% (for ADS AA ratio upper limit)
uint256 internal constant AA_RATIO_LIM_UP = 99000;
// constant to represent 50% (for ADS AA ratio lower limit)
uint256 internal constant AA_RATIO_LIM_DOWN = 50000;
// stkIDLE address
address internal constant STK_IDLE = address(0xaAC13a116eA7016689993193FcE4BadC8038136f);
// liquidity burned at first tranche deposit
uint256 internal constant MIN_LIQUIDITY = 10**3;
// Referral event
event Referral(uint256 _amount, address _ref);
// tolerance in underlyings when redeeming
uint256 internal liquidationTolerance;
// Add new variables here. For each storage slot
// used, reduce the __gap length by 1.
// #######################
// Min apr ratio for AA tranches when using AYS
uint256 internal minAprSplitAYS;
// Max strategy price decrease before triggering a default
uint256 internal maxDecreaseDefault;
// Legacy IdleCDO loss tolerance; unused by Credit Vaults and retained in their proxy layout.
uint256 internal lossToleranceBps;
// Amount of stkIDLE required to mint 1 underlying
uint256 internal stkIDLEPerUnderlying;
// Explicit flag for epoch variants using programmable borrower hooks.
// This lives in shared storage so upgrading prefunded epoch variants does not shift child storage.
bool public isProgrammableBorrower;
// annualized management fee. Max is MAX_FEE / 10
uint256 public managementFee;
// Explicit owner-controlled opt-in for BB deposits. Disabled by default.
bool public isBBDepositEnabled;
// uint256 public test;
// #######################
// This is empty reserved space in storage that is put
// in place in Upgradeable contracts. It allows us to
// freely add new state variables in the future without
// compromising the storage compatibility with existing
// deployments.
// The size of the __gap array is calculated so that the
// amount of storage used by a contract always adds up to
// always the same number, 50 in this case.
uint256[43] private __gap;
// uint256[42] private __gap; -> after adding `test`
// #######################
// IMPORTANT: Do not add any variables below `__gap`
}
contracts/IdleCDOTranche.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @dev ERC20 representing a tranche token
contract IdleCDOTranche is ERC20 {
// allowed minter address
address public minter;
// liquidity burned at first tranche deposit
uint256 internal constant MIN_LIQUIDITY = 10**3;
/// @param _name tranche name
/// @param _symbol tranche symbol
constructor(
string memory _name, // eg. IdleDAI
string memory _symbol // eg. IDLEDAI
) ERC20(_name, _symbol) {
// minter is msg.sender which is IdleCDO (in initialize)
minter = msg.sender;
}
/// @param account that should receive the tranche tokens
/// @param amount of tranche tokens to mint
function mint(address account, uint256 amount) external {
require(msg.sender == minter, '6');
// burn MIN_LIQUIDITY on first tranche deposit
if (totalSupply() == 0) {
_mint(address(1), MIN_LIQUIDITY);
amount -= MIN_LIQUIDITY;
}
_mint(account, amount);
}
/// @param account that should have the tranche tokens burned
/// @param amount of tranche tokens to burn
function burn(address account, uint256 amount) external {
require(msg.sender == minter, '6');
_burn(account, amount);
}
}
contracts/interfaces/IERC20Detailed.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IERC20Detailed is IERC20Upgradeable {
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function decimals() external view returns(uint256);
}
contracts/interfaces/IIdleCDOStrategy.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
interface IIdleCDOStrategy {
function strategyToken() external view returns(address);
function token() external view returns(address);
function tokenDecimals() external view returns(uint256);
function oneToken() external view returns(uint256);
function redeemRewards(bytes calldata _extraData) external returns(uint256[] memory);
function pullStkAAVE() external returns(uint256);
function price() external view returns(uint256);
function getRewardTokens() external view returns(address[] memory);
function deposit(uint256 _amount) external returns(uint256);
// _amount in `strategyToken`
function redeem(uint256 _amount) external returns(uint256);
// _amount in `token`
function redeemUnderlying(uint256 _amount) external returns(uint256);
function getApr() external view returns(uint256);
}
contracts/interfaces/IProgrammableBorrower.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
/// @notice Hook surface exposed by programmable borrowers used by `IdleCDOEpochVariant`.
interface IProgrammableBorrower {
/// @notice Sync borrower-side accounting when a new epoch starts.
/// @param _pendingWithdraws Underlyings reserved for withdraw requests at epoch end.
function onStartEpoch(uint256 _pendingWithdraws) external;
/// @notice Free enough liquidity so IdleCDO can pull stop-epoch funds.
/// @param _amountRequired Total underlyings IdleCDO will transfer from the borrower.
/// @param _isRequestingAllFunds Whether IdleCDO is closing the pool and recalling all funds.
/// @return success False when the borrower ledger makes close-pool settlement a real default.
function onStopEpoch(uint256 _amountRequired, bool _isRequestingAllFunds) external returns (bool success);
/// @notice Return the total net interest currently due for the running epoch.
/// @dev This is the pool-facing stop-epoch value: borrower contractual interest plus paid
/// buffer interest plus positive vault PnL minus vault losses.
/// @return Interest amount owed right now.
function totalInterestDueNow() external view returns (uint256);
/// @notice Move accrued borrower interest into settled debt.
/// @dev Called only on success path after IdleCDO fronted the interest. This settles the full
/// contractual borrower-interest sleeve, independently from vault gains or losses.
function settleBorrowerInterest() external;
/// @notice Abort active epoch accounting after IdleCDO has defaulted the facility.
/// @dev Used only on the default path when `onStopEpoch` could not complete successfully.
function onDefault() external;
}
contracts/interfaces/keyring/IKeyring.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IKeyring {
function checkCredential(uint256 policyId, address entity) external view returns (bool);
}contracts/strategies/idle/IdleCreditVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
import "../../interfaces/IIdleCDOStrategy.sol";
import "../../interfaces/IERC20Detailed.sol";
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
interface IIdleCDOEpochVariant {
function isEpochRunning() external view returns (bool);
function epochEndDate() external view returns (uint256);
function expectedEpochInterest() external view returns (uint256);
function pendingWithdrawFees() external view returns (uint256);
function fee() external view returns (uint256);
function isInterestMinted() external view returns (bool);
function getContractValue() external view returns (uint256);
function lastNAVAA() external view returns (uint256);
function lastNAVBB() external view returns (uint256);
function trancheAPRSplitRatio() external view returns (uint256);
function defaulted() external view returns (bool);
}
error NotAllowed();
contract IdleCreditVault is
Initializable,
OwnableUpgradeable,
ERC20Upgradeable,
ReentrancyGuardUpgradeable,
IIdleCDOStrategy
{
using SafeERC20Upgradeable for IERC20Detailed;
/// @notice underlying token address (pool currency for Clearpool)
address public override token;
/// @notice decimals of the underlying asset
uint256 public override tokenDecimals;
/// @notice one underlying token
uint256 public override oneToken;
/// @notice underlying ERC20 token contract (pool currency for Clearpool)
IERC20Detailed public underlyingToken;
/// @notice address of the IdleCDO
address public idleCDO;
/// @notice one year, used to calculate the APR
uint256 public constant YEAR = 365 days;
/// @notice latest saved apr, already scaled to include the buffer period
uint256 public lastApr;
/// @notice address of the borrower
address public borrower;
/// @notice address of the manager
address public manager;
/// @notice user withdraw requests
mapping (address => uint256) public withdrawsRequests;
/// @notice user instant withdraw requests
mapping (address => uint256) public instantWithdrawsRequests;
/// @notice total withdraw requests
uint256 public pendingWithdraws;
/// @notice pending instant withdraw requests
uint256 public pendingInstantWithdraws;
/// @notice counter for epoch deposits
uint256 public totEpochDeposits;
/// @notice deprecated transfer flag retained for storage compatibility
bool public canTransfer;
/// @notice last withdraw request epoch for a user
mapping (address => uint256) public lastWithdrawRequest;
/// @notice current epoch number
uint256 public epochNumber;
/// @notice unscaled apr
uint256 public unscaledApr;
/// @notice constant representing a 100% fee used for accounting
uint256 private constant FULL_ALLOC = 100_000;
/// @notice total principal for APR=0 requests in the current epoch
uint256 public apr0TotalPrincipal;
struct Apr0UserData {
uint256 principal;
uint256 principalEpoch;
uint256 settledPrincipal;
uint256 settledInterest;
}
/// @notice APR=0 withdraw data per user
mapping (address => Apr0UserData) public apr0Users;
/// @notice net APR=0 interest rate per epoch, scaled by 1e18
mapping (uint256 => uint256) public apr0RateByEpoch;
/// @notice default maximum allowed scaled apr
uint256 public constant DEFAULT_MAX_APR = 20e18;
/// @notice maximum allowed scaled apr, 0 disables the cap
uint256 public maxApr;
/// @notice underlying reserved for finalized post-default recovery claims
uint256 public defaultRecoveryReserve;
/// @notice post-default recovery ratio, scaled by 1e18
uint256 public defaultRecoveryPrice;
/// @notice strategy epoch that defaulted and was finalized for recovery
uint256 public defaultRecoveryEpoch;
/// @notice true once the CDO finalized default recovery accounting
bool public defaultRecoveryFinalized;
/// @notice true when unfunded default-epoch instant receipts were included in recovery accounting
bool public defaultInstantWithdrawsFinalized;
/// @notice normal withdraw receipt basis by user and request epoch
mapping(address => mapping(uint256 => uint256)) public withdrawsRequestsByEpoch;
/// @notice post-default withdraw requests that are already backed by default recovery reserve
mapping(address => uint256) public postDefaultRequests;
/// @notice instant withdraw receipt basis by user and request epoch
mapping(address => mapping(uint256 => uint256)) public instantWithdrawsRequestsByEpoch;
/// @notice total outstanding instant-withdraw receipt basis per request epoch
mapping(uint256 => uint256) public instantWithdrawClaimsByEpoch;
/// @notice funded recovery ratio for pending withdraw receipts haircutted by stopEpochWithDuration loss
mapping(uint256 => uint256) public lossRecoveryPriceByEpoch;
/// @notice true once default-recovery request accounting is initialized for this strategy
bool public defaultRecoveryInitialized;
/// @notice full recovery ratio scale
uint256 private constant RECOVERY_FULL = 1e18;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
token = address(1);
}
/// @notice can be only called once
/// @param _underlyingToken address of the underlying token (pool currency)
function initialize(
address _underlyingToken,
address _owner,
address _manager,
address _borrower,
string memory borrowerName,
uint256 _apr
) public virtual initializer {
OwnableUpgradeable.__Ownable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
require(token == address(0), "Token is already initialized");
//----- // -------//
token = _underlyingToken;
underlyingToken = IERC20Detailed(token);
tokenDecimals = underlyingToken.decimals();
oneToken = 10**(tokenDecimals);
borrower = _borrower;
manager = _manager;
maxApr = DEFAULT_MAX_APR;
// on the first setup we set the lastApr equal to the unscaledApr
lastApr = _apr;
unscaledApr = _apr;
defaultRecoveryInitialized = true;
// name will be like: Pareto Credit Vault Borrower
// symbol will be like: Borrower
ERC20Upgradeable.__ERC20_init(
_concat(string("Pareto Credit Vault "), borrowerName),
borrowerName
);
//------//-------//
transferOwnership(_owner);
}
/// @notice strategy token decimals
/// @dev equal to underlying token decimals
/// @return number of decimals
function decimals() public view override returns (uint8) {
return uint8(tokenDecimals);
}
/// @notice strategy token address
function strategyToken() external view override returns (address) {
return address(this);
}
/// @notice return strategy token price which is always 1
/// @return price in underlyings
function price() public view virtual override returns (uint256) {
return oneToken;
}
/// @notice current fixed apr for the epoch
function getApr() external view returns (uint256) {
return lastApr;
}
/// @notice set manager address
/// @param _manager address of the new manager
function setManager(address _manager) external onlyOwner {
manager = _manager;
}
/// @notice set borrower address
/// @param _borrower address of the new borrower
function setBorrower(address _borrower) external onlyOwner {
require(_borrower != address(0), "IS_0");
borrower = _borrower;
}
/// @notice set maximum allowed scaled apr, 0 disables the cap
/// @param _maxApr new max apr
function setMaxApr(uint256 _maxApr) external onlyOwner {
maxApr = _maxApr;
}
/// @notice set both the scaled and unscaled apr
/// @dev only cdo and manager can set the apr.
/// @param _unscaledApr unscaled apr
/// @param _apr scaled apr
function setAprs(uint256 _unscaledApr, uint256 _apr) external {
unscaledApr = _unscaledApr;
// here we also check that msg.sender is allowed
setApr(_apr);
}
/// @notice set both the unscaled APR and APR scaled by epoch plus buffer duration.
/// @dev only CDO and manager can set the APR through `setApr`.
/// @param _unscaledApr unscaled APR
/// @param _duration epoch duration
/// @param _buffer buffer duration
function setAprsWithBuffer(uint256 _unscaledApr, uint256 _duration, uint256 _buffer) external {
unscaledApr = _unscaledApr;
setApr(_duration == 0 ? _unscaledApr : _unscaledApr * (_duration + _buffer) / _duration);
}
/// @notice set the fixed apr
/// @dev only cdo and manager can set the apr. If manager manually set apr from
/// here it will not be scaled to include the buffer period
function setApr(uint256 _apr) public {
address _cdo = idleCDO;
// if cdo is not yet set we skip the check (this can happen only during the setup)
if (_cdo != address(0)) {
if (msg.sender != _cdo && msg.sender != manager) revert NotAllowed();
}
uint256 _maxApr = maxApr;
if (_maxApr != 0 && _apr > _maxApr) revert NotAllowed();
lastApr = _apr;
}
/// @notice request withdraw of underlying token from the vault
/// @dev We don't burn strategy tokens here, but we increase the withdraw requests. A user must
/// claim a loss-adjusted receipt before opening a later request so its recovery epoch is preserved.
/// @param _amount number of tokens claimable by the user
/// @param _user address of the user
/// @param _principal principal amount backing the withdraw request
function requestWithdraw(uint256 _amount, address _user, uint256 _principal) external {
_onlyIdleCDO();
_ensureDefaultRecoveryInitialized();
if (_amount == 0) return;
if (defaultRecoveryFinalized) {
// user should first claim old already-funded withdraw requests before requesting new ones after default
if (_hasWithdrawRequest(_user) || instantWithdrawsRequests[_user] != 0 || postDefaultRequests[_user] != 0) {
revert NotAllowed();
}
// Preserve request/claim UX after default without increasing borrower-facing pendingWithdraws.
// The CDO passes an already-haircut amount because finalization lowered virtualPrice first.
_burn(msg.sender, _amount);
_mint(_user, _amount);
postDefaultRequests[_user] = _amount;
return;
}
bool isClosed = IIdleCDOEpochVariant(idleCDO).epochEndDate() == 0;
uint256 currentEpoch = epochNumber;
uint256 lossEpoch = lastWithdrawRequest[_user];
uint256 lossRecoveryPrice = lossRecoveryPriceByEpoch[lossEpoch];
if (
lossRecoveryPrice != 0 &&
(withdrawsRequestsByEpoch[_user][lossEpoch] != 0 ||
(apr0Users[_user].principal != 0 && apr0Users[_user].principalEpoch == lossEpoch))
) {
// A loss-adjusted receipt must be claimed before opening a later request, otherwise
// `lastWithdrawRequest` would stop pointing to the epoch that stores its haircut.
revert NotAllowed();
}
// burn strategy tokens from cdo (we don't burn future interest here, only the principal)
_burn(msg.sender, _principal);
// mint equal amount of strategy tokens to the user as receipt (interest included), useful in case of default
_mint(_user, _amount);
// A successfully closed pool already recalled all funds and has no later stopEpoch.
if (!isClosed) {
// Global amount that stopEpoch must source from borrower/strategy for all pending receipts.
pendingWithdraws += _amount;
}
// save the epoch of the last withdraw request (buffer + epochDuration is 1 epoch)
lastWithdrawRequest[_user] = currentEpoch;
// APR=0 requests keep separate accounting and settle interest at stopEpoch.
// `_amount` here is the post-management-fee principal bucket for that flow.
if (unscaledApr == 0 && !isClosed) {
_requestWithdrawApr0(_amount, _user);
} else {
// increase the withdraw requests for the user
// we record both per-user (old, kept for compatibility) and per-epoch so
// on finalization we can distinguish "default-epoch pending receipts"
// from old funded receipts.
withdrawsRequests[_user] += _amount;
withdrawsRequestsByEpoch[_user][currentEpoch] += _amount;
}
}
/// @notice claim the withdraw request
/// @dev we burn the strategy tokens and transfer the underlying tokens
/// @param _user address of the user
/// @return amount number of tokens claimed
function claimWithdrawRequest(address _user) external returns (uint256 amount) {
_onlyIdleCDO();
if (defaultRecoveryFinalized) {
// Post-default requests are already priced after the haircut and backed by the reserve,
// so they must not fall through to the defaulted-epoch receipt logic.
amount = _claimPostDefaultWithdrawRequest(_user);
if (amount != 0) return amount;
// Only receipts created in the defaulted epoch are haircutted here; old fulfilled
// receipts are handled below at par if they were already funded before default.
amount = _claimDefaultedWithdrawRequest(_user);
}
amount += _claimLossAdjustedWithdrawRequest(_user);
return amount + _claimFundedWithdrawRequest(_user);
}
/// @notice Claim a funded non-default withdraw request at par.
/// @param _user address of the user
/// @return amount amount claimed
function _claimFundedWithdrawRequest(address _user) internal returns (uint256 amount) {
// User should wait at least an epoch before claiming the withdraw. Once the epoch is over user can withdraw
// at any time even if a new epoch started.
// So if epochNumber is the same as the last withdraw request then we revert. Epoch number is increased at stopEpoch
// NOTE: If a user does not claim a withdraw request and instead requests another withdraw, he will have to wait
// for another epoch to claim both requests.
// NOTE 2: if borrower defaults, old withdraw requests can still be claimed
if (IIdleCDOEpochVariant(idleCDO).epochEndDate() != 0 && (epochNumber <= lastWithdrawRequest[_user])) {
revert NotAllowed();
}
// settle APR=0 requests once the related epoch has ended
_settleApr0(_user);
Apr0UserData storage _apr0User = apr0Users[_user];
// Claim includes:
// - settled APR0 principal from finalized epochs
// - still-open APR0 principal: if pool-close mode was used (_interest == 1), IdleCDO sets
// epochEndDate = 0 and claims can be immediate, while _settleApr0 can still skip settlement
// for the current request epoch (reqEpoch >= epochNumber).
// - settled APR0 interest
uint256 normalAmount = withdrawsRequests[_user];
uint256 apr0PrincipalAmount = _apr0User.settledPrincipal + _apr0User.principal;
uint256 apr0InterestAmount = _apr0User.settledInterest;
amount = normalAmount + apr0PrincipalAmount + apr0InterestAmount;
// burn strategy tokens 1:1 with the principal only (normal amount already includes interest)
_burn(_user, normalAmount + apr0PrincipalAmount);
withdrawsRequests[_user] = 0;
lastWithdrawRequest[_user] = 0;
if (apr0PrincipalAmount != 0 || apr0InterestAmount != 0) {
delete apr0Users[_user];
}
_transferFundedClaim(_user, amount);
}
/// @notice request instant withdraw of underlying token from the vault
/// @dev we burn strategy tokens here, and we increase the instant withdraw requests
/// @param _amount number of tokens to withdraw
/// @param _user address of the user
function requestInstantWithdraw(uint256 _amount, address _user) external {
_onlyIdleCDO();
_ensureDefaultRecoveryInitialized();
// burn strategy tokens from cdo
_burn(msg.sender, _amount);
// mint equal amount of strategy tokens to the user as receipt, useful in case of default
_mint(_user, _amount);
// increase the instant withdraw requests for the user
instantWithdrawsRequests[_user] += _amount;
uint256 currentEpoch = epochNumber;
// we record both per-user (old, kept for compatibility) and per-epoch so on
// finalization we can distinguish "default-epoch pending instant receipts"
// from old funded instant receipts.
instantWithdrawsRequestsByEpoch[_user][currentEpoch] += _amount;
instantWithdrawClaimsByEpoch[currentEpoch] += _amount;
// increase the total instant withdraw requests
pendingInstantWithdraws += _amount;
}
/// @notice claim the instant withdraw request
/// @dev we transfer the underlying tokens
/// @param _user address of the user
function claimInstantWithdrawRequest(address _user) external {
_onlyIdleCDO();
if (defaultRecoveryFinalized && defaultInstantWithdrawsFinalized) {
// Clear the defaulted-epoch instant receipt first, then continue so the same call can
// also pay any older instant receipt that was already funded before default finalization.
_claimDefaultedInstantWithdrawRequest(_user);
}
uint256 amount = instantWithdrawsRequests[_user];
// burn strategy tokens from user
_burn(_user, amount);
instantWithdrawsRequests[_user] = 0;
_transferFundedClaim(_user, amount);
}
/// @notice collect the instant withdraw funds
/// @dev only IdleCDO can call this function
/// @param _amount number of tokens to collect
function collectInstantWithdrawFunds(uint256 _amount) external {
_onlyIdleCDO();
if (_amount == 0) return;
pendingInstantWithdraws -= _amount;
underlyingToken.safeTransferFrom(idleCDO, address(this), _amount);
}
/// @notice collect borrower-funded withdraw receipt funds
/// @dev Only IdleCDO can call this function. When `_amount` is lower than the
/// pending basis, the difference is a stopEpochWithDuration loss assigned to
/// pending receipts and users later claim through `lossRecoveryPriceByEpoch`.
/// Reverts if the resulting recovery price rounds to zero at `RECOVERY_FULL` precision.
/// @param _amount number of funded tokens to collect
function collectWithdrawFunds(uint256 _amount) external {
_onlyIdleCDO();
uint256 pendingBasis = pendingWithdraws;
if (_amount < pendingBasis) {
// Legacy receipts do not have per-epoch ownership data, so they can only be fully funded.
if (!defaultRecoveryInitialized) revert NotAllowed();
uint256 lossRecoveryPrice = _amount * RECOVERY_FULL / pendingBasis;
// Avoid storing a zero price, which is indistinguishable from "no loss-adjusted epoch".
if (lossRecoveryPrice == 0) revert NotAllowed();
pendingWithdraws = 0;
lossRecoveryPriceByEpoch[epochNumber] = lossRecoveryPrice;
} else {
// A plain implementation upgrade may leave legacy normal receipts pending. Their next
// successful stop can fully fund the aggregate before lazy initialization occurs.
pendingWithdraws = pendingBasis - _amount;
}
if (_amount != 0) {
underlyingToken.safeTransferFrom(idleCDO, address(this), _amount);
}
}
/// @notice Preview how a realized stop-epoch loss is split between active LPs and pending receipts.
/// @dev Without pending receipts, a loss cannot exceed its active basis. When pending receipts
/// exist, all pending receipts share their aggregate portion of the loss pro rata because the
/// pending bucket does not retain tranche identity. The remaining active loss is later applied
/// by the CDO through its ordinary BB-first waterfall.
/// @param _lossAmount realized loss amount
/// @return pendingToFund amount of pending withdrawals that should be funded by the borrower
/// @return activeLoss amount of loss that remains assigned to active LPs
function previewLossAdjustedWithdrawFunds(uint256 _lossAmount) external view returns (uint256 pendingToFund, uint256 activeLoss) {
uint256 pendingBasis = pendingWithdraws;
// Full zero-loss funding is safe for legacy aggregate receipts and needs no migration call.
if (_lossAmount == 0) return (pendingBasis, _lossAmount);
IIdleCDOEpochVariant cdo = IIdleCDOEpochVariant(idleCDO);
uint256 activeBasis = _lossActiveBasis(cdo);
if (pendingBasis == 0) {
if (_lossAmount > activeBasis) revert NotAllowed();
return (0, _lossAmount);
}
// Legacy pending receipts do not have the per-epoch ownership data needed to store a haircut.
if (!defaultRecoveryInitialized) revert NotAllowed();
uint256 totalBasis = activeBasis + pendingBasis;
if (_lossAmount >= totalBasis) revert NotAllowed();
uint256 pendingLoss = _lossAmount * pendingBasis / totalBasis;
pendingToFund = pendingBasis - pendingLoss;
activeLoss = _lossAmount - pendingLoss;
}
/// @notice Calculate the active basis used to split a successful stop-epoch loss.
/// @dev Minted fee shares remain backed by CDO-held strategy tokens and therefore join the
/// active-side loss. Cash mode mirrors CDO accounting: management fees are already accrued,
/// then performance fees apply only to gain above the last saved AA plus BB NAV.
/// @param _cdo epoch CDO interface
/// @return activeBasis active strategy-token basis participating in the loss
function _lossActiveBasis(IIdleCDOEpochVariant _cdo) internal view returns (uint256 activeBasis) {
if (_cdo.isInterestMinted()) {
// Accrued fees become AA shares before the loss burn, so the full CDO strategy-token
// balance plus gross minted interest participates on the active side.
return balanceOf(idleCDO) + _cdo.expectedEpochInterest();
}
uint256 activeBasisBeforePerfFee = _cdo.getContractValue();
uint256 expectedInterest = _cdo.expectedEpochInterest();
uint256 pendingFees = _cdo.pendingWithdrawFees();
if (expectedInterest > pendingFees) {
activeBasisBeforePerfFee += expectedInterest - pendingFees;
}
uint256 savedNAV = _cdo.lastNAVAA() + _cdo.lastNAVBB();
activeBasis = activeBasisBeforePerfFee > savedNAV ?
activeBasisBeforePerfFee - ((activeBasisBeforePerfFee - savedNAV) * _cdo.fee() / FULL_ALLOC) :
activeBasisBeforePerfFee;
}
/// @notice compute and apply APR=0 epoch deltas for stopEpoch
/// @param _interest stopEpoch override interest (0 = expected epoch interest, 1 = repay all)
/// @return _expInterest stopEpoch interest after APR0 adjustments
/// @return _adjPendingWithdrawFees pending withdraw fees after APR0 adjustments
function prepareStopEpochWithApr0(uint256 _interest) external returns (uint256 _expInterest, uint256 _adjPendingWithdrawFees) {
_onlyIdleCDO();
IIdleCDOEpochVariant _cdo = IIdleCDOEpochVariant(idleCDO);
uint256 _pendingFees = _cdo.pendingWithdrawFees();
uint256 _tvl = _cdo.getContractValue();
_expInterest = _interest > 1 ? _interest : _cdo.expectedEpochInterest();
_adjPendingWithdrawFees = _pendingFees;
// Principal currently waiting for withdraw that was requested while APR was 0,
// net of the upfront management fee charged at request time.
uint256 _principal = apr0TotalPrincipal;
// Fast path: no APR0 accounting needed.
if (_principal == 0) {
return (_expInterest, _adjPendingWithdrawFees);
}
// APR0 principal is only valid while APR is 0 for that request lifecycle.
if (unscaledApr != 0) {
revert NotAllowed();
}
uint256 _apr0NetInterest;
// APR0 allocation is computed only when stopEpoch receives a real override interest.
// _expectedInterest == 1 is the "request all funds back" sentinel and is handled in IdleCDO.
if (_expInterest > 1 && _expInterest > _pendingFees) {
// Remove already booked withdraw fees from the interest base before splitting.
uint256 _interestNetOfFees = _expInterest - _pendingFees;
// Total principal used for the pro-rata split:
// IdleCDO TVL (which excludes APR0 requested principal) + APR0 principal bucket.
uint256 _totalPrincipalForSplit = _tvl + _principal;
if (_totalPrincipalForSplit != 0) {
// APR0 users get a pro-rata share of realized interest.
uint256 _apr0InterestGross = _interestNetOfFees * _principal / _totalPrincipalForSplit;
if (_apr0InterestGross != 0) {
// Same fee model as normal withdraw interest.
uint256 _apr0Fee = _apr0InterestGross * _cdo.fee() / FULL_ALLOC;
_apr0NetInterest = _apr0InterestGross - _apr0Fee;
_adjPendingWithdrawFees += _apr0Fee;
_expInterest -= _apr0NetInterest;
}
}
}
// Finalize one-epoch APR0 interest for current epoch only.
if (_apr0NetInterest != 0) {
// Funds owed to withdraw requesters increase by APR0 net interest.
pendingWithdraws += _apr0NetInterest;
// Save per-epoch net rate; each APR0 request accrues exactly once on its request epoch.
apr0RateByEpoch[epochNumber] = (_apr0NetInterest * 1e18) / _principal;
}
// Close current APR0 bucket so it cannot accrue again on later stopEpoch calls.
apr0TotalPrincipal = 0;
}
/// @notice settle APR=0 requests for a user once their epoch is finalized
/// @param _user address of the user
function _settleApr0(address _user) internal {
Apr0UserData storage _apr0User = apr0Users[_user];
uint256 _principal = _apr0User.principal;
if (_principal == 0) {
return;
}
uint256 _reqEpoch = _apr0User.principalEpoch;
// Settle only after stopEpoch bumped epochNumber (ie after one full wait epoch).
if (_reqEpoch >= epochNumber) {
return;
}
// Move principal from "open APR0 bucket" to "settled bucket" (same principal, not duplicated).
_apr0User.settledPrincipal += _principal;
uint256 _rate = apr0RateByEpoch[_reqEpoch];
if (_rate != 0) {
// Convert per-epoch rate to claimable underlying interest.
_apr0User.settledInterest += (_principal * _rate) / 1e18;
}
_apr0User.principal = 0;
_apr0User.principalEpoch = 0;
}
function _requestWithdrawApr0(uint256 _amount, address _user) internal {
// Settle any previous APR0 request first, then start/update current epoch bucket.
_settleApr0(_user);
Apr0UserData storage _apr0User = apr0Users[_user];
if (_apr0User.principal == 0) {
_apr0User.principalEpoch = epochNumber;
}
_apr0User.principal += _amount;
// Epoch-level APR0 principal used only to compute stopEpoch APR0 pro-rata interest.
apr0TotalPrincipal += _amount;
}
/// @notice Send funds to the IdleCDO
/// @param _amount number of underlyings to transfer
function sendInterestAndDeposits(uint256 _amount) external {
_onlyIdleCDO();
if (_amount == 0) return;
IERC20Detailed(token).safeTransfer(idleCDO, _amount);
}
/// @notice Burn strategy tokens from the CDO
/// @param _amount number of strategy tokens (1:1 with underlyings) to burn
function burnStrategyTokens(uint256 _amount) external {
_onlyIdleCDO();
_burn(msg.sender, _amount);
}
/// @notice Get funds from IdleCDO and mint strategy tokens. Funds are not sent to the borrower here
/// @param _amount number of underlyings to transfer
function deposit(uint256 _amount)
external
virtual
override
returns (uint256) {
_onlyIdleCDO();
if (_amount > 0) {
underlyingToken.safeTransferFrom(msg.sender, address(this), _amount);
_mint(msg.sender, _amount);
}
if (IIdleCDOEpochVariant(idleCDO).isEpochRunning()) {
// deposit done on stopEpoch (before setting the var to false) so we reset the counter
totEpochDeposits = 0;
epochNumber += 1;
} else {
// deposit done between epochs so we increase the counter
totEpochDeposits += _amount;
}
return _amount;
}
/// @notice Mint strategy tokens to the CDO without moving underlyings
/// @dev Used for mid-epoch deposits that send funds directly to the borrower
function mintStrategyTokens(uint256 _amount) external {
_onlyIdleCDO();
_mint(msg.sender, _amount);
}
/// @notice Reserve already-held underlying for a later finalized default recovery.
/// @dev Called by the CDO when borrower funding fails after funds were already returned here.
/// @param _amount amount of underlying already held by this strategy for default recovery
function reserveDefaultRecovery(uint256 _amount) external {
_onlyIdleCDO();
if (defaultRecoveryFinalized) revert NotAllowed();
defaultRecoveryReserve += _amount;
}
/// @notice Total claim basis that should be haircut by default finalization.
/// @dev Normal pending withdraws are already tracked globally. Current-epoch instant receipts
/// join recovery only if `pendingInstantWithdraws` is still non-zero at finalization. This can
/// happen when startEpoch moved the CDO's available cash to the strategy but that cash covered
/// only part of the instant queue. The full current-epoch instant claim is included as basis,
/// while the already-funded part is added to the reserve by `_defaultPrefundedInstantReserve()`.
/// Receipt accounting is aggregate and does not retain AA/BB identity. IdleCDOEpochVariant
/// therefore applies one recovery multiplier to both tranche classes.
/// @return basis amount of defaulted receipt claims in underlying units
function defaultPendingClaimBasis() public view returns (uint256 basis) {
basis = pendingWithdraws;
if (pendingInstantWithdraws != 0) {
basis += instantWithdrawClaimsByEpoch[epochNumber];
}
}
/// @notice Finalize strategy-side default recovery accounting.
/// @dev Called by the CDO. `_recoverySource` must approve this strategy for `_recoveredAmount`.
/// `_recoveredAmount` is the exact external recovery to pull; already-held strategy funds
/// are added separately because they should not be pulled from `_recoverySource` again.
/// A zero or subprecision aggregate recovery finalizes at price zero. Active tranche prices are
/// then zero and pending receipts can be cleared without a payout; any positive reserve too small
/// to represent at `RECOVERY_FULL` precision remains isolated as recovery dust.
/// @param _recoveredAmount exact amount of recovered underlying supplied by `_recoverySource`
/// @param _recoverySource address that supplies recovered underlying
/// @return defaultBBNav BB's final recovered active NAV
function finalizeDefaultRecovery(uint256 _recoveredAmount, address _recoverySource) external returns (uint256 defaultBBNav) {
_onlyIdleCDO();
_ensureDefaultRecoveryInitialized();
IIdleCDOEpochVariant cdo = IIdleCDOEpochVariant(idleCDO);
if (defaultRecoveryFinalized || !cdo.defaulted()) revert NotAllowed();
if (_recoveredAmount != 0 && _recoverySource == address(0)) revert NotAllowed();
// Active holders are still represented by strategy tokens owned by the CDO. Add the
// default-epoch net interest so they use the same claim basis as pending redeemers.
// Split gross backing by saved NAV and default interest by the configured APR split.
// The CDO strategy-token balance is its gross active value before `unclaimedFees`.
// Using it directly restores those waived unpaid fees to active recovery basis.
uint256 activeBalance = balanceOf(idleCDO);
uint256 activeInterest = _defaultActiveInterestBasis(cdo);
uint256 activeBasis = activeBalance + activeInterest;
defaultBBNav = _defaultBBBasis(cdo, activeBalance, activeInterest);
// Pending receipts have already left active CDO NAV, so they are added as a separate basis.
uint256 pendingBasis = defaultPendingClaimBasis();
uint256 totalBasis = activeBasis + pendingBasis;
if (totalBasis == 0) revert NotAllowed();
// Some recovery funds may already be in this strategy: partially prefunded instant requests
// and borrower-send funds that failed at epoch start. Count both without pulling them again.
uint256 prefundedReserve = _defaultPrefundedInstantReserve();
uint256 reserveAmount = _recoveredAmount + prefundedReserve + defaultRecoveryReserve;
// Recovery can be above par if the recovered funds exceed the computed basis.
uint256 recoveryPrice = reserveAmount * RECOVERY_FULL / totalBasis;
defaultRecoveryFinalized = true;
defaultRecoveryReserve = reserveAmount;
defaultRecoveryPrice = recoveryPrice;
defaultRecoveryEpoch = epochNumber;
// A non-zero pending instant bucket means current-epoch instant receipts were not fully funded
// and must be paid through the same recovery ratio as normal pending receipts.
defaultInstantWithdrawsFinalized = pendingInstantWithdraws != 0;
// Bring active CDO NAV to the same recovery ratio. IdleCDOEpochVariant then calls
// _forceUpdateAccounting so tranche prices/virtualPrice expose the crystallized loss.
uint256 activeFinalNAV = (activeBasis * recoveryPrice) / RECOVERY_FULL;
defaultBBNav = defaultBBNav * recoveryPrice / RECOVERY_FULL;
if (activeBalance > activeFinalNAV) {
_burn(idleCDO, activeBalance - activeFinalNAV);
} else if (activeFinalNAV > activeBalance) {
_mint(idleCDO, activeFinalNAV - activeBalance);
}
if (_recoveredAmount != 0) {
// Pull external recovery last: if the transfer fails, the whole finalization reverts.
underlyingToken.safeTransferFrom(_recoverySource, address(this), _recoveredAmount);
}
}
/// @notice Get current-epoch instant-withdraw funds already collected before default finalization.
/// @dev `pendingInstantWithdraws` is the still-unfunded remainder. If it is lower than the
/// current-epoch claim basis, the difference is already-held underlying reserved for those claims.
/// @return prefundedReserve amount of current instant claims already backed by strategy underlyings
function _defaultPrefundedInstantReserve() internal view returns (uint256 prefundedReserve) {
uint256 pendingInstant = pendingInstantWithdraws;
if (pendingInstant == 0) return prefundedReserve;
uint256 instantBasis = instantWithdrawClaimsByEpoch[epochNumber];
if (instantBasis > pendingInstant) {
prefundedReserve = instantBasis - pendingInstant;
}
}
/// @notice Calculate default-epoch net interest basis for active LPs.
/// @param _cdo epoch CDO interface
/// @return activeInterest net interest basis for active LPs
function _defaultActiveInterestBasis(IIdleCDOEpochVariant _cdo) internal view returns (uint256 activeInterest) {
uint256 expectedInterest = _cdo.expectedEpochInterest();
uint256 pendingFees = _cdo.pendingWithdrawFees();
if (expectedInterest <= pendingFees) return activeInterest;
// Pending redeemers already include their net interest in pendingWithdraws; active LPs need
// the same borrower-owed interest basis, net of performance fees, before applying recovery.
activeInterest = expectedInterest - pendingFees;
activeInterest -= activeInterest * _cdo.fee() / FULL_ALLOC;
}
/// @notice Calculate BB's active claim basis before applying the default recovery multiplier.
/// @dev Gross active backing is split by saved NAV, while interest follows the configured APR split.
/// @param _cdo epoch CDO interface
/// @param _activeBalance gross active strategy-token backing
/// @param _activeInterest net active default-epoch interest
/// @return bbBasis BB's active claim basis before recovery
function _defaultBBBasis(IIdleCDOEpochVariant _cdo, uint256 _activeBalance, uint256 _activeInterest) internal view returns (uint256 bbBasis) {
uint256 savedAA = _cdo.lastNAVAA();
uint256 savedBB = _cdo.lastNAVBB();
uint256 activeBasis = _activeBalance + _activeInterest;
if (savedBB == 0 || activeBasis == 0) return bbBasis;
if (savedAA == 0) return activeBasis;
uint256 savedNAV = savedAA + savedBB;
uint256 grossBBBasis = _activeBalance * savedBB / savedNAV;
uint256 bbInterest = _activeInterest * (FULL_ALLOC - _cdo.trancheAPRSplitRatio()) / FULL_ALLOC;
bbBasis = grossBBBasis + bbInterest;
}
/// @notice Claim an already-funded post-default withdraw request.
/// @param _user address of the user
/// @return amount amount claimed from default recovery reserve
function _claimPostDefaultWithdrawRequest(address _user) internal returns (uint256 amount) {
amount = postDefaultRequests[_user];
if (amount == 0) return amount;
postDefaultRequests[_user] = 0;
// Post-default receipts are paid 1:1 because the haircut was applied when the request was made.
_burn(_user, amount);
_transferDefaultRecovery(_user, amount);
}
/// @notice Claim a defaulted normal withdraw receipt with the finalized recovery haircut.
/// @param _user address of the user
/// @return amount amount paid from default recovery reserve
function _claimDefaultedWithdrawRequest(address _user) internal returns (uint256 amount) {
uint256 defaultEpoch = defaultRecoveryEpoch;
(uint256 claimBasis, uint256 burnAmount) = _clearWithdrawClaimForEpoch(_user, defaultEpoch, true);
if (claimBasis == 0) return amount;
// pendingWithdraws stores the claim basis owed by the borrower, including APR0 interest.
pendingWithdraws -= claimBasis;
// Only receipt principal exists as strategy tokens. APR0 interest is included in claimBasis
// but was never minted as a user strategy-token receipt.
_burn(_user, burnAmount);
amount = (claimBasis * defaultRecoveryPrice) / RECOVERY_FULL;
_transferDefaultRecovery(_user, amount);
}
/// @notice Claim a stopEpochWithDuration loss-adjusted withdraw receipt.
/// @param _user address of the user
/// @return amount amount paid from funded strategy underlyings
function _claimLossAdjustedWithdrawRequest(address _user) internal returns (uint256 amount) {
uint256 lossEpoch = lastWithdrawRequest[_user];
uint256 lossRecoveryPrice = lossRecoveryPriceByEpoch[lossEpoch];
if (lossRecoveryPrice == 0) return amount;
(uint256 claimBasis, uint256 burnAmount) = _clearWithdrawClaimForEpoch(_user, lossEpoch, false);
if (claimBasis == 0) return amount;
// pendingWithdraws was already cleared when the borrower funded the loss-adjusted amount.
_burn(_user, burnAmount);
amount = (claimBasis * lossRecoveryPrice) / RECOVERY_FULL;
_transferFundedClaim(_user, amount);
}
/// @notice Clear a normal/APR0 withdraw receipt for one request epoch.
/// @dev This does not move funds or burn receipt tokens. Default claims also decrease
/// `apr0TotalPrincipal`; loss-adjusted claims do not because stopEpoch already closed that bucket.
/// @param _user address of the user
/// @param _claimEpoch epoch whose receipt should be cleared
/// @param _isClearingApr0 true when clearing an open APR0 default claim
/// @return claimBasis claim amount before applying the recovery ratio
/// @return burnAmount strategy-token receipt amount to burn
function _clearWithdrawClaimForEpoch(address _user, uint256 _claimEpoch, bool _isClearingApr0) internal returns (uint256 claimBasis, uint256 burnAmount) {
(claimBasis, burnAmount) = _withdrawClaimAmountsForEpoch(_user, _claimEpoch);
if (claimBasis == 0) return (claimBasis, burnAmount);
uint256 normalAmount = withdrawsRequestsByEpoch[_user][_claimEpoch];
if (normalAmount != 0) {
withdrawsRequestsByEpoch[_user][_claimEpoch] = 0;
// The aggregate may also include older funded receipts; clear only this epoch's piece.
withdrawsRequests[_user] -= normalAmount;
}
Apr0UserData storage apr0User = apr0Users[_user];
if (apr0User.principal != 0 && apr0User.principalEpoch == _claimEpoch) {
if (_isClearingApr0) {
uint256 apr0Principal = apr0User.principal;
uint256 totalApr0Principal = apr0TotalPrincipal;
// prepareStopEpochWithApr0 may already close the global APR0 bucket before default finalization.
apr0TotalPrincipal = apr0Principal >= totalApr0Principal ? 0 : totalApr0Principal - apr0Principal;
}
apr0User.principal = 0;
apr0User.principalEpoch = 0;
}
if (lastWithdrawRequest[_user] == _claimEpoch) {
// The cleared epoch was the latest request marker. Any remaining normal/APR0 receipt
// is older and already funded, so it can continue to the funded-claim path.
lastWithdrawRequest[_user] = 0;
}
}
/// @notice Claim a defaulted instant-withdraw receipt with the finalized recovery haircut.
/// @param _user address of the user
/// @return claimBasis amount of instant-withdraw basis cleared
function _claimDefaultedInstantWithdrawRequest(address _user) internal returns (uint256 claimBasis) {
uint256 defaultEpoch = defaultRecoveryEpoch;
claimBasis = instantWithdrawsRequestsByEpoch[_user][defaultEpoch];
if (claimBasis == 0) return claimBasis;
instantWithdrawsRequestsByEpoch[_user][defaultEpoch] = 0;
instantWithdrawsRequests[_user] -= claimBasis;
uint256 pending = pendingInstantWithdraws;
// `pendingInstantWithdraws` is only the unfunded remainder. If this user's claim is larger,
// the extra amount was already counted as prefunded reserve during default finalization.
pendingInstantWithdraws = claimBasis >= pending ? 0 : pending - claimBasis;
instantWithdrawClaimsByEpoch[defaultEpoch] -= claimBasis;
_burn(_user, claimBasis);
_transferDefaultRecovery(_user, (claimBasis * defaultRecoveryPrice) / RECOVERY_FULL);
}
/// @notice Get defaulted normal/APR0 withdraw claim basis and receipt burn amount.
/// @param _user address of the user
/// @return claimBasis claim amount before recovery haircut
/// @return burnAmount strategy-token receipt amount to burn
function _withdrawClaimAmountsForEpoch(address _user, uint256 _claimEpoch) internal view returns (uint256 claimBasis, uint256 burnAmount) {
// We calculate what the user is owed in underlyings (claimBasis) and how many strategy tokens to burn (burnAmount).
// the amount owned is the sum of the normal withdraw request and the APR0 principal and interest if any.
uint256 normalAmount = withdrawsRequestsByEpoch[_user][_claimEpoch];
Apr0UserData storage _apr0User = apr0Users[_user];
uint256 apr0PrincipalAmount;
uint256 apr0InterestAmount;
uint256 principal = _apr0User.principal;
uint256 principalEpoch = _apr0User.principalEpoch;
if (principal != 0 && principalEpoch == _claimEpoch) {
apr0PrincipalAmount = principal;
uint256 rate = apr0RateByEpoch[principalEpoch];
if (rate != 0) {
// APR0 interest increases the user's default claim basis, but not the receipt burn amount.
apr0InterestAmount += (principal * rate) / RECOVERY_FULL;
}
}
claimBasis = normalAmount + apr0PrincipalAmount + apr0InterestAmount;
burnAmount = normalAmount + apr0PrincipalAmount;
}
/// @notice Check if a user has a normal or APR0 withdraw request.
/// @param _user address of the user
/// @return true if a normal or APR0 request exists
function _hasWithdrawRequest(address _user) internal view returns (bool) {
Apr0UserData storage data = apr0Users[_user];
return withdrawsRequests[_user] != 0 ||
data.principal != 0 ||
data.settledPrincipal != 0 ||
data.settledInterest != 0;
}
/// @notice Transfer a funded claim without spending default recovery reserve.
/// @param _user claim receiver
/// @param _amount amount to transfer
function _transferFundedClaim(address _user, uint256 _amount) internal {
if (_amount == 0) return;
uint256 reserve = defaultRecoveryReserve;
if (reserve != 0) {
uint256 balance = underlyingToken.balanceOf(address(this));
// This should be unreachable when accounting is consistent. Keep the guard so old funded
// receipts can never spend underlyings reserved for default recovery claimants.
if (balance < reserve || balance - reserve < _amount) revert NotAllowed();
}
underlyingToken.safeTransfer(_user, _amount);
}
/// @notice Transfer default recovery reserve to a user.
/// @param _user claim receiver
/// @param _amount amount to transfer
function _transferDefaultRecovery(address _user, uint256 _amount) internal {
if (_amount == 0) return;
// Every defaulted or post-default claim consumes the isolated recovery reserve.
defaultRecoveryReserve -= _amount;
underlyingToken.safeTransfer(_user, _amount);
}
/// @notice Lazily initialize recovery accounting for an upgraded strategy.
/// @dev Legacy pending receipts must first be fully funded because their per-epoch ownership
/// cannot be reconstructed after an implementation upgrade. A successfully closed vault has
/// already recalled all funds, so stale normal/APR0 aggregate counters can be normalized there.
/// Pending instant withdrawals are never cleared automatically.
function _ensureDefaultRecoveryInitialized() internal {
if (defaultRecoveryInitialized) return;
if (pendingInstantWithdraws != 0) revert NotAllowed();
if (pendingWithdraws != 0) {
IIdleCDOEpochVariant cdo = IIdleCDOEpochVariant(idleCDO);
if (cdo.epochEndDate() != 0 || cdo.defaulted()) revert NotAllowed();
pendingWithdraws = 0;
apr0TotalPrincipal = 0;
}
defaultRecoveryInitialized = true;
canTransfer = false;
}
/// @inheritdoc ERC20Upgradeable
/// @dev Receipt claims are address-bound, so only the IdleCDO can move strategy tokens.
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
if (msg.sender != idleCDO) revert NotAllowed();
super._transfer(sender, recipient, amount);
}
/// @notice Clear the deprecated receipt-token transfer flag.
/// @dev Kept for upgrade compatibility. Enabling transfers is permanently disabled because
/// receipt claims are address-bound; the manager may only clear a legacy `true` value.
/// @param _canTransfer must be false
function setCanTransfer(bool _canTransfer) external {
if (msg.sender != manager || _canTransfer) revert NotAllowed();
canTransfer = false;
}
/// @notice allow to update whitelisted address
function setWhitelistedCDO(address _cdo) external onlyOwner {
require(_cdo != address(0), "IS_0");
idleCDO = _cdo;
}
/// @notice Emergency method to rescue funds
/// @param _token address of the token to transfer
/// @param value amount of `_token` to transfer
/// @param _to receiver address
function transferToken(address _token, uint256 value, address _to) external onlyOwner {
IERC20Detailed(_token).safeTransfer(_to, value);
}
/// @notice Modifier to make sure that caller os only the idleCDO contract
function _onlyIdleCDO() internal view {
if (msg.sender != idleCDO) {
revert NotAllowed();
}
}
/// @notice concat 2 strings in a single one
/// @param a first string
/// @param b second string
/// @return new string with a and b concatenated
function _concat(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
/// @notice Not used as redeems happens only via requestWithdraw and requestInstantWithdraw
function redeem(uint256 _amount)
external
override
returns (uint256) {}
/// @notice Not used as redeems happens only via requestWithdraw and requestInstantWithdraw
function redeemUnderlying(uint256)
external
returns (uint256) {}
/// @notice not used in this strategy
function pullStkAAVE()
external
pure
override
returns (uint256) {}
/// @notice not used for this strategy
function getRewardTokens()
external
view
override
returns (address[] memory) {}
/// @notice not used for this strategy
function redeemRewards(bytes calldata)
external
override
returns (uint256[] memory rewards) {}
}
Compiler settingsShow
{
"optimizer": {
"runs": 1,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.