Verified contractExactUNLICENSED
IdleCreditVault
Address0xbba97a1ca6d4966870cbe9f032ae9c6e6546d2ee
- 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, 999,999 runs
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,027,298
- Creation transaction
- 0x783c7facb6…b6bb541f41
15 files
- contracts/strategies/idle/IdleCreditVault.solmain47.94 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 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
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol3.53 KB
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol1.29 KB
- contracts/interfaces/IERC20Detailed.sol363 B
- contracts/interfaces/IIdleCDOStrategy.sol884 B
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) {}
}
@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/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;
}
@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/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);
}
Compiler settingsShow
{
"optimizer": {
"runs": 999999,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.